【问题标题】:zip dict.items() of mutiple dicts in a list?zip dict.items() 列表中的多个字典?
【发布时间】:2016-11-25 16:17:05
【问题描述】:

我认为这应该很容易,但找不到简单而优雅的解决方案。 我有这个:

l = [{1: 1, 2: 2},
     {'a': 'a', 'b': 'b'}]

我想要这个:

l = [((1, 1), ('a', 'a')),
     ((2, 2), ('b', 'b'))]

如何将列表中多个 dicts 的项目压缩在一起?

【问题讨论】:

  • 类似zip(*map(dict.items, l))。请注意,字典中键的顺序可能会发生变化。
  • 这正是我所需要的,也可以与 OrderedDict 一起使用以保持秩序。请张贴作为答案。
  • @barrios 我们的输出列表的顺序重要吗?
  • 是的。我想知道是否可以通过理解来达到相同的效果?

标签: python dictionary zip items


【解决方案1】:

Python 3

在 Python 3 中,dict.items 返回一个 dict_items 对象。为了防止这种情况,您可以通过以下方式将它们全部转换为元组:

list(zip(*map(dict.items, l)))

zip(*<iterable>) 将可迭代扩展为 zip 的参数,然后 zip 将参数压缩为元组(有效地将所有值转换为元组)。

但是,这会在此过程中非常冗余地构建多个列表。这可以通过以下方式避免:

list(map((lambda d: tuple(d.items())), l))
# Or with multiple maps:
list(map(tuple, map(dict.items, l))))

可以说,这更直观,但确实使用lambda 或多个映射,因此对于较小的字典列表效率较低。

Python 2

在 Python 2 中,dict.items 返回一个 list。如果您不是特别需要列表上的元组,将它们保留为列表就可以了,map(dict.items, l) 就足够了。

在这里,您可以执行与上述相同的操作(省略list(...),因为zip 返回一个列表:

zip(*map(dict.items, l))

您也可以简单地映射tuple

map(tuple, map(dict.items, l))
# Or with a lambda:
map((lambda d: tuple(d.items())), l)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2011-05-04
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多