Feyzi Bagirov
Feyzi Bagirov

Reputation: 1372

Iterating through list of dictionaries to extract specific key/values in python

I have a list of dictionaries:

lofd = [{'a':'123', 'b':'abc', 'c': {'ca':['1','2'],'cb':['3','4']},'d':{'da':['1','2'], 'db':['1','2']}]

I need to iterate through it to extract it into a new dataset:

new_lofd = [{'a':'123', 'c':{'ca':['1','2'], 'd':{'db':['1','2']}]

How do I access specific key/values in a loop?

Upvotes: 0

Views: 1143

Answers (2)

pylang
pylang

Reputation: 44485

You have a nested data-structure, which is generally tricky to pluck specific items. In your case:

  1. iterate each level
  2. create new sub-dicts of white-listed keys
  3. merge the sub-dicts together

See the annotated example below.

Given

lofd = [
    {"a": "123", 
     "b": "abc", 
     "c": {"ca": ["1", "2"],
           "cb": ["3", "4"]},
     "d": {"da": ["1", "2"], 
           "db": ["1", "2"]}
    }
]
#      ^     ^
#      |     |___ level II   
#      \__________level I

Selecting desired keys per level:

level_i_keys = {"a", "c", "d"}
level_ii_keys = {"ca", "db"}

Code

res = {}
for k, v in lofd[0].items():                                                # 1  
    if k not in level_i_keys:
        continue
    if not isinstance(v, dict):
        sub = {k: v}                                                        # 2
    else:
        sub = {k: {k2: v2 for k2, v2 in v.items() if k2 in level_ii_keys}}  # 1, 2
    res.update(sub)                                                         # 3


new_lofd = [res]
new_lofd

Output

[
    {"a":"123", 
     "c": {"ca":["1","2"]}, 
     "d": {"db":["1","2"]}
    }
]

Upvotes: 1

wang hulin
wang hulin

Reputation: 36

You could first transform the loft list into a dictionary like this

lofd = [{'a':'123', 'b':'abc', 'c': {'ca':['1','2'],'cb':['3','4']},'d':{'da':['1','2'], 'db':['1','2']}}]
      dic = lofd[0]

and a simple loop will do the job for you. Otherwise, you cannot directly iterate through your list since it only has one huge dictionary element in it.

Upvotes: 0

Related Questions