【问题标题】:Python List to Dictionary conversion via Comprehension通过理解将 Python 列表转换为字典
【发布时间】:2014-04-10 18:55:45
【问题描述】:

假设我有一个返回字典的函数,然后我遍历该函数。这将产生一个字典列表。我希望将其转换为字典。我这样调用我的函数:

x = [_myfunction(element) for element in list_of_elements]

导致说 x:

x = [{'one': {'two':'2'}, 'three' : '3'}, {'four':'five', 'six':{'seven':7}}]

我希望转换成 y:

y = {'one': {'two':'2'}, 'three' : '3', 'four':'five', 'six':{'seven':7}}

有没有一种方法可以通过 list_of_elements 调用 _myfunction(),从而直接产生 y?也许用字典理解而不是上面的列表理解?或者将 x 转换为 y 的最简洁的代码是什么。 (希望不要无聊并使用 for 循环!:-))

谢谢,实验室迷

【问题讨论】:

  • y 是字典的元组,几乎没有改进。您是否想要一个字典,其中包含键 'one''three''four''six'
  • 你想要的 y 不是字典,它是 2 个元素的元组(2 个字典)。
  • 如果你真的想要一本字典,你必须告诉我们当一个键出现在两个(或更多)字典中时你想做什么。
  • 哎呀,你是对的。我已经纠正了。在相同键的情况下,可以覆盖。

标签: python list dictionary dictionary-comprehension


【解决方案1】:

您可以使用dict.update 方法合并字典:

y = {}
for element in list_of_elements:
  y.update(_myfunction(element))

您也可以使用(双循环)dict-comprehension:

y = {
    k:v
    for element in list_of_elements
    for k,v in _myfunction(element).items()
}

最后,如果您对this question 的任何一个答案,用于合并两个字典(并将其命名为merge_dicts),您可以使用reduce 来合并两个以上:

dicts = [_myfunction(element) for element in list_of_elements]
y = reduce(merge_dicts, dicts, {})

无论哪种方式,在重复 dict 键的情况下,后面的键会覆盖前面的键

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2016-10-25
    • 2022-12-04
    • 2011-11-18
    • 2022-08-16
    相关资源
    最近更新 更多