Reputation: 403
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
Upvotes: 0
Views: 6053
Reputation: 21759
You can do classic dict comprehension here:
signames = {k: '_'+ v for k,v in signames.items()}
Upvotes: 1
Reputation: 107134
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
Upvotes: 3
Reputation: 4137
This is wrong key = str(_) + key
since the signmaes
dictionary is never updated. Just change this line to signames[key] = '_' + value
.
Upvotes: 0