【问题标题】:python 2.7 create dictionary key from tuplepython 2.7 从元组创建字典键
【发布时间】:2017-05-07 13:49:35
【问题描述】:

如何在 Python 2.7 中从元组创建有序字典键?

我看过很多关于从元组创建新字典或从字典键构建元组的示例,但没有看到如何从元组生成“多维键”,即使用元组中的键递归索引嵌套字典。

基本上我想使用一个元组,例如:

('australia', 'queensland', 'brisbane')

作为字典键:

places['australia']['queensland']['brisbane']

字典是一个包含 JSON 数据的 OrderedDict。

【问题讨论】:

  • 你的意思是places 是一个dicts of dicts 的dicts 吗?
  • 这不是一个非常难的问题,但价值是多少?
  • 到目前为止你尝试过什么?请参考:How to Ask。请发布minimal reproducible example。在询问之前,您甚至都懒得完成 2 分钟的实地考察

标签: python python-2.7 tuples


【解决方案1】:

一个衬里(t 是您的元组,places 是您的字典字典...):

reduce(dict.get, t, places)

这里实际发生的是,您从字典 places 重复 getting 元组 t 的每个元素。

在 python 3 中,您需要通过 from functools import reduce 导入 reduce。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2017-10-16
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多