【问题标题】:Fast way to create a nested dictionary from a list of tuples without a for loop从没有 for 循环的元组列表中创建嵌套字典的快速方法
【发布时间】:2022-10-07 23:39:44
【问题描述】:

我知道以前有人问过类似的问题,但我找不到适合我的情况的答案。

假设我有以下元组列表:

d = [('first', 1), ('second', 2), ('third', 3)]

我可以很容易地将其转换为字典:

dict(d)
# {'first': 1, 'second': 2, 'third': 3}

现在,如果我有以下元组列表:

d = [('a', 'first', 1), ('a', 'second', 2), ('b', 'third', 3)]

我怎样才能最有效地获得以下嵌套字典:

{'a': {'first': 1, 'second': 2}, 'b': {'third': 3}}

这是我现在的解决方案:

from collections import defaultdict
dd = defaultdict(dict)
for a, b, c in d:
    dd[a][b] = c
# defaultdict(dict, {'a': {'first': 1, 'second': 2}, 'b': {'third': 3}})

这是执行此操作的最高效方式吗?是否可以避免for循环? 很可能我必须处理d 非常大的情况,并且这种方法可能无法很好地扩展。这部分对我正在构建的 Web 应用程序至关重要,这就是性能非常重要的原因。

输入/反馈/帮助表示赞赏!

【问题讨论】:

  • 您可以避免显式的for 循环,但某种形式的循环是不可避免的。
  • 我相信你是对的。但是,如果我必须选择,那么我会比我自己更信任 python 来执行循环。

标签: python python-3.x list python-collections


【解决方案1】:

你可以用groupby

from itertools import groupby
result = {k:dict([(i[1],i[2]) for i in l]) for k, l in groupby(d, key=lambda x: x[0])}

# Result
{'a': {'first': 1, 'second': 2}, 'b': {'third': 3}}

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 2019-09-30
    • 2021-07-25
    • 2019-03-29
    • 2022-01-03
    • 2019-04-23
    • 1970-01-01
    相关资源
    最近更新 更多