我有一个字典列表,它们都具有相同的键,例如
input = [
{
"animal": "Tiger"
"country": "US",
"color": "yellow-black"
},
{
"animal": "Dog"
"country": "UK",
"color": "brown"
},
{
"animal": "Tiger"
"country": "Nepal",
"color": "yellow-black"
}
]
我想创建一个新字典,其中对指定键(此处为动物)共享相同值的字典组合在一起。在对它们进行分组时,我想从初始词典中删除“动物”键。对于给定的例子,它会喜欢这个
output = {
"Tiger":
[{
"country": "US",
"color": "yellow-black"
},
{
"animal": "Tiger"
"country": "Nepal",
"color": "yellow-black"
}],
"Dog": [
{
"country": "UK",
"color": "brown"
}]
}
我用下面的代码实现了这一点,但我很确定必须有一种更优雅的方法来解决这个问题。是否可以将其写为单行?
grouped = dict((k, list(g)) for k, g in itertools.groupby(input, key=lambda x:x['animal']))
for k, g in grouped.items():
for i in range(len(grouped)):
del g[i]['animal']
森林海
BIG阳
撒科打诨
相关分类