用列表替换字典值

时间:2019-01-27 13:54:24

标签: python python-3.x dictionary

像这样的字典:

{' ': None, 'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'g': None, 'h': None, 'i': None, 'j': None, 'k': None, 'l': None, 'm': None, 'n': None, 'o': None, 'p': None, 'q': None, 'r': None, 's': None, 't': None, 'u': None, 'v': None, 'w': None, 'x': None, 'y': None, 'z': None}  

还有一个

list = [0,1,2,....26] 

我想用列表中的值替换所有值None
这样我们就可以决定

{'': 0, 'a' :1....'z': 26}

1 个答案:

答案 0 :(得分:0)

您可以像这样使用循环或字典理解:

d = {' ': None, 'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'g': None, 'h': None, 'i': None, 'j': None, 'k': None, 'l': None, 'm': None, 'n': None, 'o': None, 'p': None, 'q': None, 'r': None, 's': None, 't': None, 'u': None, 'v': None, 'w': None, 'x': None, 'y': None, 'z': None}  
l = [x for x in range(len(d.keys()))]
d2 = { k:l[i] for i, k in enumerate(d.keys()) }
print(d2)
# Outputs:
# {' ': 0, 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}