0

I have a python dictionary called signames with thousands of key value pairs. A truncated version:

signames = {'A_13342_2674_14_': '13342-2674-14.03-0-2-1', 'A_13342_2675_14_': '13342-2675-14.03-0-2-1', 'A_13342_2676_14_': '13342-2676-14.03-0-2-1'}

I want to append the character _ to the beginning all values within the python dictionary so that the final dictionary would look like:

signames = {'A_13342_2674_14_': '_13342-2674-14.03-0-2-1', 'A_13342_2675_14_': '_13342-2675-14.03-0-2-1', 'A_13342_2676_14_': '_13342-2676-14.03-0-2-1'}

My code produces no error but doesn't update the values:

for key, value in signames.items():
    key = str(_) + key

3 Answers 3

3

Your key variable holds only the value of each key of the dict for each iteration, and if you assign a new value to the key, it only updates that key variable, not the dict. You should update the dict itself by referencing the key of the dict in each assignment:

for key in signames:
    signames[key] = '_' + signames[key]

But as @jpp pointed out in the comment, it would be more idiomatic to iterate over signames.items() instead, since the expression in the assignment also involves the value of each key:

for key, value in signames.items():
    signames[key] = '_' + value
Sign up to request clarification or add additional context in comments.

3 Comments

It's more idiomatic to iterate over signames.items(), since your logic involves both key and value.
Thank you-- I understand that explanation!
@jpp Indeed. Updated as suggested then. Thanks.
1

You can do classic dict comprehension here:

signames = {k: '_'+ v for k,v in signames.items()}

Comments

0

This is wrong key = str(_) + key since the signmaes dictionary is never updated. Just change this line to signames[key] = '_' + value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.