RohitM
RohitM

Reputation: 137

Get dictionary value from multiple dictionaries in a list

I have a list of many dictionaries with only one key value pair like below.

List1 = [{'dept': 'a'}, {'country': 'India'}, {'name':'xyz'}, {'age':32}]

I want to extract name from this list by not using index number but with the dict key.

Can anyone help me out?

Upvotes: 1

Views: 2079

Answers (2)

S.B
S.B

Reputation: 16476

Try this:

List1 = [{'dept': 'a'}, {'country': 'India'}, {'name': 'xyz'}, {'age': 32}]

for dic in List1:
    name = dic.get('name')
    if name is not None:    # {'name': ''} which is acceptable.
        break
        
print(name)

output :

xyz

Upvotes: 4

DYZ
DYZ

Reputation: 57033

Or use list comprehesion. It always looks better than a loop.

[dic['name'] for dic in List1 if 'name' in dic][0]

Upvotes: 3

Related Questions