我有一个字典列表,其中所有字典都具有相同的键,例如
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']
请您参考如下方法:
最简单的方法可能是使用 defaultdict .我假设您实际上想在输出中删除 "animal" 标签,因为您在输入中也缺少逗号,所以很可能是错字。
from collections import defaultdict
output = defaultdict(list)
inp = [
{
"animal": "Tiger",
"country": "US",
"color": "yellow-black"
},
{
"animal": "Dog",
"country": "UK",
"color": "brown"
},
{
"animal": "Tiger",
"country": "Nepal",
"color": "yellow-black"
}
]
for item in inp:
output[item['animal']].append({k: v for k, v in item.items()
if k != 'animal'})
根据您的字典中有多少键/值对,简单地从字典中删除键可能会更快,而不是使用字典理解来重建不包括该键的字典。对于这种大小的样本,速度真的无关紧要,也不会冒更改初始数据的风险。
