Iterate over list of dictionaries and find matching elements from a list and append value of matching key to defaultdict

流过昼夜 提交于 2019-12-11 07:51:24

问题


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' : 3,
'i' : 5,
'j' : 3}

I have another list called list_to_match which only holds some letters: ['a', 'f', 'x']

I need to iterate over list_of_dict and find the keys that match with the element in the list and append the values to a an empty defaultdict of list items. If not found, append 0 to the list.

The defaultdict is initialized as:

d = collections.defaultdict(list)

I want the eventual defaultdict to look like:

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

So far, I have:

for ld in list_of_dict:
    for match in list_to_match:
        for k, v in ld.items():
            d[match].append(v)
    d[match].append(0)

Now all of this works apart from the last line because obviously, match does not exist in that scope. Now, all I get in the defaultdict is:

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

The 0 is missing and so is x. How do I fix it?


回答1:


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 = {}
for match in 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]}



回答2:


You can use a dictionary comprehension:

{i: [j[i] if i in j else 0 for j in list_of_dict] for i in 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}



回答3:


IIUC, you can just do:

for m in list_to_match:
    d[m] = [ld.get(m, 0) for ld in 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.



来源:https://stackoverflow.com/questions/52977459/iterate-over-list-of-dictionaries-and-find-matching-elements-from-a-list-and-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!