【问题标题】:How to return the values of dictionary key that has gained new values in a different dictionary如何返回在不同字典中获得新值的字典键的值
【发布时间】:2018-11-15 10:41:47
【问题描述】:

我的问题有点类似于:Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key

但就我而言,我有两本字典

dict1 = {'foo' : ['val1' , 'val2' , 'val3'] , 'bar' : ['val4' , 'val5']}

dict2 = {'foo' : ['val2', 'val10', 'val11'] , 'bar' : ['val1' , 'val4']}

我要返回的是

dict3 = {'foo' : ['val10', 'val11'] , 'bar' : ['val1']}

反之

dict4 = {'foo' : ['val1', 'val3'] , 'bar' : ['val5']}

其中 dict3 返回键 'foo' 和 'bar' 在 dict2 中获得的值的字典,而 dict4 是键 'foo' 和 'bar' 在 dict2 中丢失的值的字典

我尝试解决的一种方法是:

 iterate over both dictionaries then
    if key of dict1 == key of dict2
       return the values of the key in dict1 and compare with the values in dict2
       return the values that aren't in both 
       as a dictionary of the key and those values

这个想法行不通,而且显然效率很低。我希望有一种更有效的工作方式来做到这一点

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    两个 dict 理解可以解决问题:

    dict3 = {k: [x for x in v if x not in dict1[k]] for k, v in dict2.items()}
    print(dict3)
    # {'foo': ['val10', 'val11'], 'bar': ['val1']}
    
    dict4 = {k: [x for x in v if x not in dict2[k]] for k, v in dict1.items()}
    print(dict4)
    # {'foo': ['val1', 'val3'], 'bar': ['val5']}
    

    上述两种推导式基本上是从键中过滤掉另一个字典中不存在的值,这是双向完成的。

    你也可以这样做没有 dict理解:

    dict3 = {}
    for k,v in dict2.items():
        dict3[k] = [x for x in v if x not in dict1[k]]
    
    print(dict3)
    # {'foo': ['val10', 'val11'], 'bar': ['val1']}
    
    dict4 = {}
    for k,v in dict1.items():
        dict4[k] = [x for x in v if x not in dict2[k]]
    
    print(dict4)
    # {'foo': ['val1', 'val3'], 'bar': ['val5']}
    

    【讨论】:

    • 谢谢。这很清楚并且有效。有什么地方可以让我学习更多的dict理解吗?
    • @Mykel 您可以尝试关注www.datacamp.com/community/tutorials/python-dictionary-comprehension。这是一个关于字典的很好的教程,包括字典理解。另请注意,您不必使用 dict 理解,它们只是方便快速制作一个衬里。没有它们也可以轻松完成上述操作,只是需要更多代码。
    • 我知道其他方法需要更多代码。然而,字典理解非常方便,我希望能理解更多。再次感谢
    • @Mykel 是的,它们非常方便。如果您了解列表推导,它们是相同的想法,只是语法略有不同。没问题的人:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2021-12-11
    • 2022-08-05
    • 1970-01-01
    相关资源
    最近更新 更多