0
votes

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, i.e. 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.

1
Do you mean that places is a dict of dicts of dicts? - Andras Deak
It's not a very hard problem in general, though what is the value? - luk32
What have you tried so far? Please refer to: How to Ask. Please post a minimal reproducible example. You also didn't even bother to complete the 2-minute site tour before asking - T-Heron

1 Answers

1
votes

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 getting each element of the tuple t from the dict places.

In python 3, you'll need to import reduce via from functools import reduce.