我想创建一个字典,该字典在单词中存储50个州的全名,并在值中存储缩写,并给出名称和缩写的列表。我希望有一个像{'Alabama':'AK','Alaska':'AL',...}这样的字典。我试过了
state_to_abbrev = {}
for word in states:
for i in range(50):
state_to_abbrev[word] = states[i]
state_to_abbrev[word] = abbreviations[i]
state_to_abbrev
我得到{'Alabama':'WY',
'阿拉斯加':'WY',
'亚利桑那州':'WY',
'阿肯色州':'WY',
'California':'WY',
'Colorado':'WY',
'Connecticut':'WY',
'特拉华州':'怀俄明州',
'Florida':'WY',
'乔治亚州':'怀俄明州',
“夏威夷”:“怀俄明州”,....}
最佳答案
你可以试试:
state_to_abbrev = {}
for word in states:
for i in range(50):
state_to_abbrev[states[i]] = abbreviations[i]
state_to_abbrev
更新:
如评论中所建议,您不需要单词的额外循环,您可以尝试以下操作:
state_to_abbrev = {}
for i in range(50):
state_to_abbrev[states[i]] = abbreviations[i]
state_to_abbrev
然后,使用
dict comprehension
您可以为上述循环分配一行:state_to_abbrev = {states[i]:abbreviations[i] for i in range(50)}
另外,由于您使用的是两个列表,因此可以尝试使用
zip
,也可以在documentation中查找示例:dict(zip(states,abbreviations))
关于python - 从列表向字典分配值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49227337/