如何在 Python 中的两个词典之间获取多个共享项?
How can I get multiple shared items between two dictionaries in Python?
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}
谢谢。
intersection = count_word.keys() & length_word.keys()
outcome = dict((k, count_word[k]) for k in intersection)
尝试获取交集(常用键)。一个你有公共密钥从 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}
使用 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)
您应该使用 .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}
只是另一个 dict comp:
outcome = {k: v for k, v in count_word.items() if k in length_word}
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}
谢谢。
intersection = count_word.keys() & length_word.keys()
outcome = dict((k, count_word[k]) for k in intersection)
尝试获取交集(常用键)。一个你有公共密钥从 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}
使用 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)
您应该使用 .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}
只是另一个 dict comp:
outcome = {k: v for k, v in count_word.items() if k in length_word}