I have a list of dicts:
[{"app1": "value1"},{"app2": "value2"},{"app1": "value3"},{"app1": "value4"}, {"app3": "value5"}]
How can I get all values of a certain key in a list? So for example for "app1" it should become something like:
{"app1":["value1", "value3", "value4"]}
For "app2" it just becomes:
{"app2":["value2"]}
CodePudding user response:
Use a defaultdict
with a nested for
loop
from collections import defaultdict
d = defaultdict(list)
lst = [{"app1": "value1"},{"app2": "value2"},{"app1": "value3"},{"app1": "value4"}, {"app3": "value5"}]
for i in lst:
for k,v in i.items():
d[k].append(v)
print(dict(d))
{'app1': ['value1', 'value3', 'value4'], 'app2': ['value2'], 'app3': ['value5']}
CodePudding user response:
You can use a list comprehension to get all the values for a given key:
>>> data = [{"app1": "value1"},{"app2": "value2"},{"app1": "value3"},{"app1": "value4"}, {"app3": "value5"}]
>>> {"app1": [d["app1"] for d in data if "app1" in d]}
{'app1': ['value1', 'value3', 'value4']}
And if you want to accumulate it all into a single dict that's just putting the list comprehension inside a dict comprehension:
>>> {k: [d[k] for d in data if k in d] for d in data for k in d}
{'app1': ['value1', 'value3', 'value4'], 'app2': ['value2'], 'app3': ['value5']}
CodePudding user response:
a = [{"app1": "value1"},{"app2": "value2"},{"app1": "value3"},{"app1": "value4"}, {"app3": "value5"}] #list of dicts
k = "app1" #key to look for
out = {k: []}
for item in a:
for key in list(item):
if key == k:
out[k].append(item[key])
print(out)
{'app1': ['value1', 'value3', 'value4']}