Skip to main content
 首页 » 编程设计

python之从列表中将值分配到字典中

2024年09月07日7pander-it

我想创建一个字典,在单词中存储 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', '佛罗里达':'怀俄明州', '格鲁吉亚':'WY', '夏威夷':'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))