JacobIRR JacobIRR - 1 year ago 61
Python Question

Ensure list of dicts has a dict with key for each key in list

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.


mylist=['this', 'that', 'these', 'those']


How do I know that mydictlist is missing the "those" key? Once I know that, I can append {'those':4} to mylist. Simply checking for "those" won't work since the list is dynamic. The data structure cannot change.


Answer Source

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 sets themselves), you can just unpack all the dicts 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 dicts), you can use collections and itertools to get remaining counts:

from collections import Counter
from itertools import chain

c = Counter(mylist)
# 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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download