How do I create an ordered dictionary key from a tuple in Python 2.7?
I have seen a lot of examples about creating a new dictionary from a tuple, or building tuples from dictionary keys but not how to generate a "multi-dimensional key" from a tuple, ie use the keys in the tuple to recursively index into a nested dictionary.
Basically I would like to use a tuple such as:
('australia', 'queensland', 'brisbane')
as a dictionary key:
places['australia']['queensland']['brisbane']
The dictionary is an OrderedDict that contains JSON data.
One liner (where t
is your tuple and places
is your dictionary of dictionaries of dictionaries of...):
reduce(dict.get, t, places)
What's actually happening here is that you're repeatedly get
ting each element of the tuple t
from the dict places
.
In python 3, you'll need to import reduce via from functools import reduce
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.