简体   繁体   English

python 2.7从元组创建字典键

[英]python 2.7 create dictionary key from tuple

How do I create an ordered dictionary key from a tuple in Python 2.7? 如何在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. 字典是一个包含JSON数据的OrderedDict。

One liner (where t is your tuple and places is your dictionary of dictionaries of dictionaries of...): 一个衬里( t是您的元组,而places是您的...的字典的字典):

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 . 实际发生的是,您反复从dict places get元组t每个元素。

In python 3, you'll need to import reduce via from functools import reduce . 在python 3中,您需要from functools import reduce

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM