【问题标题】:Comparing two dictionaries and returning new dictionaries比较两个字典并返回新字典
【发布时间】:2020-05-24 14:48:54
【问题描述】:

目的:比较两个字典并返回带有COUNTRIES键和Country_gdps值的第三个字典,如果country_gdps键匹配COUNTRIES值,否则从country_gdps中删除所有键值对。

给定字典sn-p,列表很长,有很多国家,只是添加了这个作为例子

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}。例如 {"Arab World": 2504702625568, "Caribbean small states": 66707362091} 不应该出现在新字典中。

【问题讨论】:

  • “如何修复此代码”是什么意思?它有什么问题?请描述您期望的输出以及发生的情况。

标签: python


【解决方案1】:

假设您想将 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}

这是您想要的还是需要其他东西,请告诉我

【讨论】:

  • 我已根据您的要求编辑代码。如果我的答案是您的解决方案,请务必将其标记为您的答案
【解决方案2】:

纠正您的 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'}

欢迎提出任何其他疑问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多