简体   繁体   中英

How to create a dictionary from a list of dictionary using specific keys in Python

I need to extract specific keys:values from a list of dictionary and then create a 'new dictionary' in Python.

I know how to create a 'new dictionary' from a single dictionary (extracting keys 'a' and 'c' and their associated values):

# Single dictionary
d1 = {"c": 3, "a": 1, "b": 2, "d": 4}
d11 = dict((i, d1[i])
           for i in ["a", "c"] if i in d1)
print(d11)

Output:

{'a': 1, 'c': 3}

But if I have a list of dictionary like this:

# List of dictionary
d2 = [{"c": 3, "a": 1, "b": 2, "d": 4},
      {"a": 100,  "c": 300, "b": 200, "d": 400},
      {"b": 'Ball', "c": 'Cat', "d": 'Doll', "a": 'Apple'}]

How can I extract and output the keys 'a' and 'c' and their associated values like this:

[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]

I have tried this:

d22 = dict((k, d2[k])
           for k in ["a", "c"] if k in d2)

But it returns an empty dictionary:

{}

Try to use:

d2 = [{"c": 3, "a": 1, "b": 2, "d": 4},
      {"a": 100,  "c": 300, "b": 200, "d": 400},
      {"b": 'Ball', "c": 'Cat', "d": 'Doll', "a": 'Apple'}]

filter_list = ["a", "c"]

d22 = [{k: d[k] for k in filter_list} for d in d2]
print(d22)

Print:

[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM