Reputation: 137
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
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
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