比较两个字典并返回新字典

时间:2020-05-24 14:48:54

标签: python

目的:如果并且当COUNTRIES的键与Country_gdps的值匹配时,比较两个字典并返回第三个字典,其键为country_gdps和值COUNTRIES,否则删除所有键来自country_gdps的值对。

给出词典摘要,此列表包含许多国家/地区,很长,仅以示例为例

country_gdps : {"Arab World": 2504702625568, "Caribbean small states": 66707362091,"Italy": 1858913163927, "Jamaica": 14056908749} 

COUNTRIES ={'ad': 'Andorra', 'ae': 'United Arab Emirates', 'af','it': 'Italy','jp': 'Japan'}

我尝试定义的函数,该函数仅适用于最后一个键-值对

def compare(dict1,dict2):
    for key1,value1 in dict1.items():
    for key2 ,value2 in dict2.items():
    if key1 == dict2[key2]:
    key1 = key2
    dict3 = {key1: value1}
    return dict3 

print(compare(country_gdps,COUNTRIES))

我想要一本新字典,当dict1的键与dict2的值匹配且不应包含dict1的键值对不匹配时,其内容应类似于result = {''it':1858913163927}例如{“阿拉伯世界”:2504702625568,“加勒比小州”:66707362091}在新词典中不应该存在。

2 个答案:

答案 0 :(得分:0)

假设您要将country_gdps的密钥与COUNTRY的值进行匹配,则代码如下:

   country_gdps ={"Arab World": 2504702625568, "Caribbean small states": 66707362091,"Italy": 1858913163927, "Jamaica": 14056908749} 

COUNTRIES ={'ad': 'Andorra', 'ae': 'United Arab Emirates','it': 'Italy','jp': 'Japan'}


dict1={}
for i in country_gdps:
    for j in COUNTRIES :
        if i == COUNTRIES[j]:
            dict1[j]=country_gdps[i]

print(dict1)

输出:

{'it': 1858913163927}

这是您想要的还是其他要求,请告诉我

答案 1 :(得分:0)

纠正您的COUNTRIES词典中的错误。

country_gdps = {"Arab World": 2504702625568, "Caribbean small states": 66707362091,"Italy": 1858913163927, "Jamaica": 14056908749} 
COUNTRIES ={'ad': 'Andorra', 'ae': 'United Arab Emirates','it': 'Italy','jp': 'Japan'}

def compare(d1,d2,d):
    for i in d1.values():
        for j in d2.keys():
            if i == j:
                d[i] = j
                return d
    else:
        country_gdps = {}
        return country_gdps
print(compare(COUNTRIES,country_gdps,{}))

输出将为

{'Italy': 'Italy'}

欢迎其他任何疑问。