检查Python中的价值和键 [英] Checking values and keys in Python
本文介绍了检查Python中的价值和键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的词典:
dict = {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Menny','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring']
等等。
如果我要检查,如果有一些值是在它们的键2列出的常见的。我该怎么办?
If I want to check if there's some values that are common between 2 lists in their keys. what should I do?
例如, 在a和c有Menny......
For example, in a and c there's "Menny"...
推荐答案
我要建一个逆指数:
from collections import defaultdict
reverse = defaultdict(set)
for key, values in dct.items():
for value in values:
reverse[value].add(key)
现在,你可以发现,在关键点之间共享的任何值:
Now you can find any value that is shared between keys:
for value, keys in reverse.items():
if len(keys) > 1:
print(value, keys)
演示:
>>> from collections import defaultdict
>>> dct = {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Menny','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring']}
>>> reverse = defaultdict(set)
>>> for key, values in dct.items():
... for value in values:
... reverse[value].add(key)
...
>>> for value, keys in reverse.items():
... if len(keys) > 1:
... print(value, keys)
...
Menny {'c', 'a'}
如果你想测试两个键,使用方法:
If you want to test two keys, use:
def check_keys(dct, key1, key2):
return not set(dct[key1]).isdisjoint(dct[key2])
演示:
>>> check_keys(dct, 'a', 'c')
True
>>> check_keys(dct, 'a', 'b')
False
,或返回的共同价值观:
or, returning the common values:
def values_intersection(dct, key1, key2):
return set(dct[key1]).intersection(dct[key2])
演示:
>>> values_intersection(dct, 'a', 'c')
{'Menny'}
>>> values_intersection(dct, 'a', 'b')
set()
这篇关于检查Python中的价值和键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文