Skip to content Skip to sidebar Skip to footer

Iterate Over List Of Dictionaries And Find Matching Elements From A List And Append Value Of Matching Key To Defaultdict

I have a list of dictionaries. Let's call it: list_of_dict. The dictionaries in the list are in the form: {'a' : 1, 'b' : 5, 'c' : 3, 'd' : 6} and {'a' : 3, 'f' : 2, 'g' : 1, 'h'

Solution 1:

You can use a dictionary comprehension:

{i: [j[i] if i in j else0forjin list_of_dict] foriin list_to_match}

Yields:

{'a': [1, 3], 'f': [0, 2], 'x': [0, 0]}

Even simpler:

{i: [j.get(i, 0) for j in list_of_dict] for i in list_to_match}

Solution 2:

You could do this, no need to use defaultdict:

list_of_dict = [{'a': 1, 'b': 5,
                 'c': 3,
                 'd': 6}, {'a': 3,
                           'f': 2,
                           'g': 1,
                           'h': 3,
                           'i': 5,
                           'j': 3}]

list_to_match = ['a', 'f', 'x']

d = {}
formatchin list_to_match:
    for ld in list_of_dict:
        d.setdefault(match, []).append(ld.get(match, 0))

print(d)

Output

{'a': [1, 3], 'x': [0, 0], 'f': [0, 2]}

Solution 3:

IIUC, you can just do:

formin list_to_match:
    d[m] = [ld.get(m, 0) forldin list_of_dict]
print(d)
#defaultdict(list, {'a': [1, 3], 'f': [0, 2], 'x': [0, 0]})

This would also work for a regular dictionary if you didn't want to use a defaultdict.

Post a Comment for "Iterate Over List Of Dictionaries And Find Matching Elements From A List And Append Value Of Matching Key To Defaultdict"