如果我有这样的字典:
dict = {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Menny','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring']
等等。
如果我想检查其键中的两个列表之间是否存在一些共同的值。我该怎么办?
例如, 在a和c中有“Menny”......
答案 0 :(得分:4)
我会构建一个反向索引:
from collections import defaultdict
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)
演示:
>>> 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'}
如果要测试两个键,请使用:
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
或者,返回常用值:
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()
答案 1 :(得分:1)
def check(value, dictionary, keys):
return all(value in dictionary[key] for key in keys)
演示:
>>> def check(value, dictionary, keys):
return all(value in dictionary[key] for key in keys)
>>> d= {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Menny','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring']}
>>> check('Menny', d, ['a', 'b'])
False
>>> check('Menny', d, ['a', 'c'])
True
>>>
如果您想拥有共享值的键:
def check(value, d):
keys_found = []
for k,v in d.items():
if value in v:
keys_found.append(k)
return keys_found
演示:
>>> def check(value, d):
keys_found = []
for k,v in d.items():
if value in v:
keys_found.append(k)
return keys_found
>>> check('Menny', d)
['c', 'a']