-2

So I am bit new to Python. I am dealing with a problem I want to call the key ['name'] and get the following result:

['Tom', 'Mark' 'Pam'] 

However i seem to be in a little trouble due to multiple dictionaries in a list as seen in the code bellow.

people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5}, {'name': "Pam", 'age': 7} ] 

Thanks in advance!

0

1 Answer 1

1

You can use a list comprehension :

>>> [i['name'] for i in people if 'name' in i] ['Tom', 'Mark', 'Pam'] 
Sign up to request clarification or add additional context in comments.

4 Comments

Given that 'name' exists in every inner dict, [i['name'] for i in people] would be enough
@BhargavRao >>> [i['a'] for i in people] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a'
@BhargavRao ahan! .... :D
@BhargavRao yep, really! i understand that ,!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.