简体   繁体   中英

How to select only specific key-value pairs from a list of dictionaries?

This is my example:

dictlist = [{'Name': 'James', 'city': 'paris','type': 'A' }, 
            {'Name': 'James','city': 'Porto','type': 'B'},
            {'Name': 'Christian','city': 'LA','type': 'A'}]

I want to filter specific keys and values.

For example:

desiredKey = [Name,type]

desiredoutput = [{'Name': 'Lara', 'type': 'A' }, 
            {'Name': 'James', 'type': 'B'},
            {'Name': 'Christian','type': 'A'}]

I tried this, but it doesn't work

keys =  dictlist[0].keys()
output= [d for d in dictlist if d.keys in desiredKey]

you can try something like this:

In [1]: dictlist = [{'Name': 'James', 'city': 'paris','type': 'A' },  
   ...:             {'Name': 'James','city': 'Porto','type': 'B'}, 
   ...:             {'Name': 'Christian','city': 'LA','type': 'A'}]                                                                                                                                         

In [2]: keys = ["Name","type"]                                                                                                                                                                              

In [3]: res = []                                                                                                                                                                                            

In [5]: for dict1 in dictlist: 
   ...:     result = dict((k, dict1[k]) for k in keys if k in dict1) 
   ...:     res.append(result) 
   ...:                                                                                                                                                                                                     

In [6]: res                                                                                                                                                                                                 
Out[6]: 
[{'Name': 'James', 'type': 'A'},
 {'Name': 'James', 'type': 'B'},
 {'Name': 'Christian', 'type': 'A'}]

It's a bit more complicated than this answer but you can also use zip and itemgetter .

In [43]: list_of_dicts = [
    ...:   {"a":1, "b":1, "c":1, "d":1},
    ...:   {"a":2, "b":2, "c":2, "d":2},
    ...:   {"a":3, "b":3, "c":3, "d":3},
    ...:   {"a":4, "b":4, "c":4, "d":4}
    ...: ]

In [44]: allowed_keys = ("a", "c")

In [45]: filter_func = itemgetter(*allowed_keys)

In [46]: list_of_filtered_dicts = [
    ...:   dict(zip(allowed_keys, filter_func(d)))
    ...:   for d in list_of_dicts
    ...: ]

In [47]: list_of_filtered_dicts
Out[47]: [{'a': 1, 'c': 1}, {'a': 2, 'c': 2}, {'a': 3, 'c': 3}, {'a': 4, 'c': 4}]

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