AP70
AP70

Reputation: 103

How to iterate over particular keys in a dict to get values

I have a large list containing many dictionaries. Within each dictionary I want to iterate over 3 particular keys and then dump into a new list. The keys are the same for each dict.

For example, I'd like to grab keys c, d, e from all the dicts in List below, output to List2.

List = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6...},
        {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60...},
        {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600...},]

List2 = [{'c':3, 'd':4, 'e':5},
         {'c':30, 'd':40, 'e':50},
         {'c':300, 'd':400, 'e':500}]

Upvotes: 1

Views: 83

Answers (2)

rafaelc
rafaelc

Reputation: 59274

Try this code:

keys = ['c', 'd']  
for dictionary in List1:
        d = {}
        for key in dictionary:
            if key in keys:
                d[key] = dictionary[key]
        List2.append(d)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You can use a nested dict comprehension:

keys = ('c', 'd', 'e')
[{k: d[k] for k in keys} for d in List]

If those keys may be missing, you can use a dictionary view object (dict.viewkeys() in Python 2, dict.keys() in Python 3) to find an intersection to only include keys that are actually present:

keys = {'c', 'd', 'e'}
[{k: d[k] for k in d.viewkeys() & keys} for d in List]

Demo:

>>> List = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6},
...         {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60},
...         {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600}]
>>> keys = ('c', 'd', 'e')
>>> [{k: d[k] for k in keys} for d in List]
[{'c': 3, 'e': 5, 'd': 4}, {'c': 30, 'e': 50, 'd': 40}, {'c': 300, 'e': 500, 'd': 400}]
>>> List = [{'a':1, 'b':2, 'd':4, 'e':5, 'f':6},
...         {'a':10, 'b':20, 'c':30, 'd':40, 'f':60},
...         {'a':100, 'b':200, 'e':500, 'f':600}]
>>> keys = {'c', 'd', 'e'}
>>> [{k: d[k] for k in d.viewkeys() & keys} for d in List]
[{'e': 5, 'd': 4}, {'c': 30, 'd': 40}, {'e': 500}]

Upvotes: 6

Related Questions