Checking Values And Keys In Python
If I have a dictionary like this: dict = {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Menny','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring'] and so on. If I wan
Solution 1:
I'd build an inverse index:
from collections import defaultdict
reverse = defaultdict(set)
for key, valuesin dct.items():
forvalueinvalues:
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)
Demo:
>>>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():...iflen(keys) > 1:...print(value, keys)...
Menny {'c', 'a'}
If you want to test two keys, use:
defcheck_keys(dct, key1, key2):
returnnotset(dct[key1]).isdisjoint(dct[key2])
Demo:
>>> check_keys(dct, 'a', 'c')
True>>> check_keys(dct, 'a', 'b')
False
or, returning the common values:
defvalues_intersection(dct, key1, key2):
returnset(dct[key1]).intersection(dct[key2])
Demo:
>>> values_intersection(dct, 'a', 'c')
{'Menny'}
>>> values_intersection(dct, 'a', 'b')
set()
Solution 2:
defcheck(value, dictionary, keys):
returnall(value in dictionary[key] for key in keys)
Demo:
>>>defcheck(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
>>>
If you want to have the keys which shared the values:
def check(value, d):
keys_found = []
for k,v in d.items():
if value in v:
keys_found.append(k)
return keys_found
Demo:
>>> defcheck(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']
Post a Comment for "Checking Values And Keys In Python"