【问题标题】:How can I get multiple shared items between two dictionaries in Python?如何在 Python 中的两个字典之间获取多个共享项?
【发布时间】:2021-03-10 17:29:50
【问题描述】:
length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4} 
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}

intersection = length_word.items() - count_word.items() 
common_words = {intersection}

错误:TypeError: unhashable type: 'set'

我希望得到这本词典:

outcome = {'pen':10, 'bird':50, 'computer':3, 'mail':12}

谢谢。

【问题讨论】:

标签: python loops dictionary intersection


【解决方案1】:

您应该使用.keys() 而不是.items()。 这是一个解决方案:

length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
intersection = count_word.keys() & length_word.keys()    

common_words = {i : count_word[i] for i in intersection}

#Output: 
{'computer': 3, 'pen': 10, 'mail': 12, 'bird': 50}

【讨论】:

    【解决方案2】:
    intersection = count_word.keys() & length_word.keys()    
    
    outcome = dict((k, count_word[k]) for k in intersection)
    

    【讨论】:

      【解决方案3】:

      尝试获取交叉点(通用键)。一个您拥有公共密钥的人可以从count_words 访问这些密钥。

      res = {x: count_word.get(x, 0) for x in set(count_word).intersection(length_word)}
      

      分辨率:

      {'bird': 50, 'pen': 10, 'computer': 3, 'mail': 12}
      

      【讨论】:

      • 为什么默认使用get 而不是count_word[x]
      • @superbrain:实际上是的,如果您要进行联合,请使用get。对于这种情况,不需要使用 get 所以是的,也可以直接使用。
      【解决方案4】:

      只是另一个 dict comp:

      outcome = {k: v for k, v in count_word.items() if k in length_word}
      

      【讨论】:

        【解决方案5】:

        使用 for 循环检查键是否存在于两个字典中。如果是,则将该键、值对添加到新字典中。

        length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
        count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
        my_dict = {}
        
        for k, v in count_word.items():
            if k in length_word.keys():
                my_dict[k] = v
        
        print(my_dict)
        

        【讨论】:

        • 为什么不简单地if k in length_word:
        • 是的,我们可以做到。你能解释一下两者之间有什么区别吗?
        • 嗯,我想说不同之处在于一种方法会做无用的额外工作,而另一种则不会:-)。我不知道你为什么做那额外的工作,只有你知道。
        • 我的意思是,.keys() 每次都会无益地创建一个键视图对象,并且整个条件的后半部分会检查键是否在您刚刚从中获取的字典中。跨度>
        • 是的,你是对的。我更正了我的代码。谢谢。
        猜你喜欢
        • 2015-12-25
        • 2011-10-13
        • 1970-01-01
        • 1970-01-01
        • 2016-11-20
        • 2014-07-05
        • 2020-07-23
        • 1970-01-01
        • 2016-01-29
        相关资源
        最近更新 更多