How to append string to existing values in Python dictionary

Question:

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
Asked By: ENIAC-6

||

Answers:

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
Answered By: blhsing

You can do classic dict comprehension here:

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

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

Answered By: b-fg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.