Home > Mobile >  Extract part of a dictionary within a list by string condition in python
Extract part of a dictionary within a list by string condition in python

Time:10-30

I have a list with dictionary contained within it in the format:

mydataset =
[{'thing1': 'pink',
  'thing2': apple,
  'thing3': 'car',
  'data': [{'firstname': 'jenny',
    'lastname': 'jones',
    }]},
{'thing1': 'blue',
  'thing2': banana,
  'thing3': 'bicycle',
  'data': [{'firstname': 'david',
    'lastname': 'walls',
    }]}]

I want to be able to extract all the items called 'firstname' within 'data'. ie jenny and david.

I've tried an approach of myextract = [ x in x if mydataset['data'] ]

but of course it fails because I think I'm looking for a value with that. My mental model of the data structure isn't right at the moment. Any help appreciated.

CodePudding user response:

Use the following list comprehension:

res = [di["firstname" ]for d in mydataset for di in d["data"] if "firstname" in di]
print(res)

Output

['jenny', 'david']

The above list comprehension is equivalent to the following for-loop:

res = []
for d in mydataset:
    for di in d["data"]:
        if "firstname" in di:
            res.append(di["firstname"])

print(res)

CodePudding user response:

Try the following:


res = [i['data'][0]['firstname'] for i in mydataset]

output:

['jenny', 'david']
  • Related