修改字典中的所有值

Alc*_*ott 5 python dictionary

代码如下:

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}
Run Code Online (Sandbox Code Playgroud)

还有其他办法吗?

PS.上面的代码只是一个简单的代码来展示我的问题.

Ach*_*him 11

这样的事情可能会使您的代码更具可读性:

dict([(x,y) for y,x in enumerate('cbad')])
Run Code Online (Sandbox Code Playgroud)

但是你应该详细说明你真正想做的事情.如果字符中的字符s不符合键,则代码可能会失败d.所以d只是键的容器,值并不重要.在这种情况下,为什么不从列表开始呢?

  • 尼斯.您也可以省略括号. (2认同)