Context:
I'm using an Ajax call to return some complex JSON from a python module. I have to use a list of keys and confirm that a list of single-item dicts contains a dict with each key.
Example:
mylist=['this', 'that', 'these', 'those']
mydictlist=[{'this':1},{'that':2},{'these':3}]
Simple code is to convert your search list to a set, then use differencing to determine what you're missing:
missing = set(mylist).difference(*mydictlist)
which gets you missing
of {'those'}
.
Since the named set
methods can take multiple arguments (and they need not be set
s themselves), you can just unpack all the dict
s as arguments to difference
to subtract all of them from your set
of desired keys at once.
If you do need to handle duplicates (to make sure you see each of the keys
in mylist
at least that many time in mydictlist
's keys, so mylist
might contain a value twice which must occur twice in the dict
s), you can use collections
and itertools
to get remaining counts:
from collections import Counter
from itertools import chain
c = Counter(mylist)
c.subtract(chain.from_iterable(mydictlist))
# In 3.3+, easiest way to remove 0/negative counts
c = +c
# In pre-3.3 Python, change c = +c to get the same effect slightly less efficiently
c += Counter()