Thomas Perkov Thomas Perkov - 3 days ago 4
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:

dataDict[:][person]


Where
":"
would be 'all keys'.

I would prefer not using a loop

Answer

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()]
Comments