【问题标题】:Best way to combine a list of dicts into one dict in python? [duplicate]在python中将字典列表组合成一个字典的最佳方法? [复制]
【发布时间】:2017-04-16 18:35:04
【问题描述】:

一段时间以来,我一直在处理一长串 dicts,但似乎无法弄清楚如何按照我想要的方式对其进行排序。这是一个较短的示例:

artist_movement = [
{'movement': 'Abstract Expressionism', 'artist': 'William Baziotes'}, 
{'movement': 'Modern Art', 'artist': 'Alexander Calder'}, 
{'movement': 'Abstract Expressionism', 'artist': 'Grace Hartigan'},
{'movement': 'Cubism', 'artist': 'Pablo Picasso'}, 
{'movement': 'Cubism', 'artist': 'Peter Blume'}, 
{'movement': 'Abstract Expressionism', 'artist': 'Norman Wilfred Lewis'},
{'movement': 'Modern Art', 'artist': 'Lucian Freud'}
]

我想以与此类似的方式按动作对艺术家进行排序:

artist_by_movement = [
{'Abstract Expressionism':['William Baziotes', 'Grace Hartigan', 'Norman Wilfred Lewis']},
{'Modern Art':['Alexander Calder', 'Lucian Freud']},
{'Cubism':['Peter Blume', 'Pablo Picasso']}
]

感谢您的帮助!

【问题讨论】:

  • this 有帮助吗?
  • 请注意,您的 Artists_by_movement 字典不能按书面方式工作。同一个键有多个值,它们会相互覆盖。
  • @djangonoob 是的,那肯定会更好。
  • @djangonoob 尝试这样的事情:artist_by_movement2 = [{'抽象表现主义':['William Baziotes', 'Grace Hartigan', 'Norman Wilfred Lewis']}, {'Modern Art':[ 'Alexander Calder', 'Lucian Freud']}, {'Cubism':['Peter Blume', 'Pablo Picasso']}] ##因为运动和艺术家的关系一直存在,它暗示着结构和你不需要明确使用“运动”作为键。
  • @Reid 谢谢。这会给我一些目标,因为我一直在努力。还在学习!我编辑了我的问题以反映您建议的格式。

标签: python list dictionary merge


【解决方案1】:

您可以使用defaultdict 创建一个字典,其键是动作,值是该动作中的艺术家列表。 defaultdict 所做的只是在看到新键时自动创建一个列表。

import collections

artist_movement = [
{'movement': 'Abstract Expressionism', 'artist': 'William Baziotes'}, 
{'movement': 'Modern Art', 'artist': 'Alexander Calder'}, 
{'movement': 'Abstract Expressionism', 'artist': 'Grace Hartigan'},
{'movement': 'Cubism', 'artist': 'Pablo Picasso'}, 
{'movement': 'Cubism', 'artist': 'Peter Blume'}, 
{'movement': 'Abstract Expressionism', 'artist': 'Norman Wilfred Lewis'},
{'movement': 'Modern Art', 'artist': 'Lucian Freud'}
]

artist_by_movement = collections.defaultdict(list)
for d in artist_movement:
    artist_by_movement[d['movement']].append(d['artist'])

如果您想要一个更传统的原始词典索引(也许其中有更多有趣的信息),您可以这样做

artist_by_movement = collections.defaultdict(list)
for d in artist_movement:
    artist_by_movement[d['movement']].append(d)

【讨论】:

  • 像魅力一样工作!非常感谢。
猜你喜欢
  • 2022-11-30
  • 2011-11-08
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 2020-07-29
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多