我一直在处理一长串的词汇,似乎无法理解如何按照我喜欢的方式对其进行排序。这是一个较短的例子:
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']}
]
感谢您的帮助!
答案 0 :(得分:4)
您可以使用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'])
创建一个字典,其键是移动,值是该移动中的艺术家列表。所有defaultdict都会在看到新密钥时自动创建一个列表。
artist_by_movement = collections.defaultdict(list)
for d in artist_movement:
artist_by_movement[d['movement']].append(d)
如果你想要一个更传统的原始词典索引(也许还有更多有趣的信息),你可以做到
var seed = () => {
if (Details.find().count() === 0) {
for (let i = 0; i < 10; i++) {
Details.insert({
name: `Detail #${i}`
});
. . .