【问题标题】:Extract keys from nested dictionary in Python从 Python 中的嵌套字典中提取键
【发布时间】:2016-05-15 05:04:53
【问题描述】:

我正在尝试编写一个单行代码来从 python 中的 2 级嵌套字典中提取键。

这是我的数据示例:

values = [(u'Andy', OrderedDict([(u'en', 102)])), (u'Ben', OrderedDict([(u'es', 1)])), (u'Jane', OrderedDict([(u'EN', 719), (u'en', 969)])), (u'Steve', OrderedDict([(u'fr', 1)])), (u'Susanne', OrderedDict([(u'nl', 2)]))]

预期的结果是:

[u'en', u'es', u'EN', u'fr', u'nl']

到目前为止我已经尝试过:

map(lambda x: x[1].keys(), values.items())
AttributeError: 'unicode' object has no attribute 'keys'

reduce(lambda k, v: v.keys(), values.items())
AttributeError: 'tuple' object has no attribute 'keys'

当我在 Jinja 模板中插入代码时,这需要是单行的,因此我正在尝试使用 lambda。不过,我对 Python 还是很陌生,也许我误解了什么……?

【问题讨论】:

  • 结果需要保持顺序吗?
  • 嗨@timgeb 不需要保留订单。

标签: python dictionary lambda key reduce


【解决方案1】:

试试这个 -

In [10]: reduce(lambda x,y:x+y ,map(lambda x:x[1].keys(), values))
Out[10]: [u'en', u'es', u'EN', u'en', u'fr', u'nl']

map 正在从字典中获取所有密钥。
reduce 负责组合嵌套列表的结果。

如果您需要唯一值(销毁订单),请使用set-

In [11]: list(set(reduce(lambda x,y:x+y ,map(lambda x:x[1].keys(), values))))
Out[11]: [u'fr', u'en', u'nl', u'es', u'EN']

【讨论】:

    【解决方案2】:

    values 不是字典,它是一个没有items 属性的列表。这是itertools.chain.from_iterable 的一种解决方案:

    >>> list(set(chain.from_iterable(x[1].keys() for x in values)))
    [u'fr', u'en', u'nl', u'es', u'EN']
    

    【讨论】:

      【解决方案3】:

      另一种解决方案

      list(set([y for x in values for y in x[1].keys()]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-06
        • 2021-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2019-11-18
        • 2021-05-10
        相关资源
        最近更新 更多