Thomas Perkov Thomas Perkov - 1 year ago 72
Python Question

Retrieve an item in all dictionaries inside another dictionary without using loops

I have dictionaries inside another dictionary like:

dataDict = {"id42": {"fruit": "banana", "person": "Jason"}, "id43": {"fruit": "apple", "person": "Thomas"} }

Now I'll like to retrieve 'Jason' and 'Thomas' without using a loop, I'm looking for something like:


would be 'all keys'.

I would prefer not using a loop

Answer Source

You can't do this without a loop. There is no : syntax for Python dictionaries (and even in lists, you need to loop, in the list implementation, to satisfy slices).

Just loop, either using map() to do the looping (if you only need an iterable), or use a list comprehension (if you must have a list):

from operator import itemgetter

results_iterable = map(itemgetter('person'), dataDict.values())

results_list = [sub['person'] for sub in dataDict.values()]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download