用另一个字典的键替换一个字典中的键

时间:2018-09-25 01:24:00

标签: dictionary python-3.6 dictionary-comprehension

假设我有2本字典:

第1区:

statedict = {'Alaska': '02', 'Alabama': '01', 'Arkansas': '05', 'Arizona': '04', 'California':'06', 'Colorado': '08', 'Connecticut': '09','DistrictOfColumbia': '11', 'Delaware': '10', 'Florida': '12', 'Georgia': '13', 'Hawaii': '15', 'Iowa': '19', 'Idaho': '16', 'Illinois': '17', 'Indiana': '18', 'Kansas': '20', 'Kentucky': '21', 'Louisiana': '22', 'Massachusetts': '25', 'Maryland': '24', 'Maine': '23', 'Michigan': '26', 'Minnesota': '27', 'Missouri': '29', 'Mississippi': '28', 'Montana': '30', 'NorthCarolina': '37', 'NorthDakota': '38', 'Nebraska': '31', 'NewHampshire': '33', 'NewJersey': '34', 'NewMexico': '35', 'Nevada': '32', 'NewYork': '36', 'Ohio': '39', 'Oklahoma': '40', 'Oregon': '41', 'Pennsylvania': '42', 'PuertoRico': '72', 'RhodeIsland': '44', 'SouthCarolina': '45', 'SouthDakota': '46', 'Tennessee': '47', 'Texas': '48', 'Utah': '49', 'Virginia': '51', 'Vermont': '50', 'Washington': '53', 'Wisconsin': '55', 'WestVirginia': '54', 'Wyoming': '56'}

第2区:

master_dict = {'01': ['01034','01112'], '06': ['06245', '06025, ''06007'], '13': ['13145']}

*实际的master_dict更长。 基本上,我想用keys中的长名称键替换master_dict中的两位数字statedict。我该怎么做呢?我正在尝试使用以下内容,但效果不佳。

for k, v in master_dict.items():
    for state, fip in statedict.items():
        if k == fip:
        master_dict[k] = statedict[state]

1 个答案:

答案 0 :(得分:1)

您可以使用字典理解来创建将值映射到键的查找表。第二个字典推导执行查找以单词替换数字:

        com.SRPS

        |-------- Misc Codes ( folder to store codes)

        |-------- GUI (Java Swing codes goes here)

        |--------- DB ( .sql files in this folder)

输出:

lookup = {v: k for k, v in statedict.items()}
result = {lookup[k]: v for k, v in master_dict.items()}
print(result)

尝试here