Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify all values in a dictionary

Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

like image 388
Alcott Avatar asked Aug 18 '11 08:08

Alcott


Video Answer


2 Answers

Something like this might make your code more readable:

dict([(x,y) for y,x in enumerate('cbad')])

But you should give more details what you really want to do. Your code will probably fail if the characters in s do not fit the keys of d. So d is just a container for the keys and the values are not important. Why not start with a list in that case?

like image 198
Achim Avatar answered Sep 26 '22 01:09

Achim


use update() method of dict:

d.update((k,s.index(k)) for k in d.iterkeys())
like image 29
HYRY Avatar answered Sep 26 '22 01:09

HYRY