[英]Adding values of the same key in different dictionaries in a list
I have a list of dictionaries:我有一个字典列表:
my_list = [
{"Name": "John Doe", "Amount": 150},
{"Name": "Peter Doe", "Amount": 40},
{"Name": "Peter Doe", "Amount": 10},
{"Name": "Lisa Doe", "Amount": 90},
{"Name": "John Doe", "Amount": 200},]
I want to iterate through the list of dictionaries and find the same values for the key "Name" if the values are the same, I want to add the "Amounts" and save it to a new dictionary.我想遍历字典列表并为键“Name”找到相同的值,如果值相同,我想添加“Amounts”并将其保存到新字典中。 For example, the list above should become:
例如,上面的列表应该变成:
my_list_2 = [
{"Name": "John Doe", "Amount": 350},
{"Name": "Peter Doe", "Amount": 50},
{"Name": "Lisa Doe", "Amount": 90},]
Would anyone please suggest any Pythonic ways of doing it?有人可以建议任何 Pythonic 的方法吗?
Thanks a lot!非常感谢!
Would you be open to use dataframe to accomplish this?您愿意使用 dataframe 来完成此任务吗?
my_list = [
{"Name": "John Doe", "Amount": 150},
{"Name": "Peter Doe", "Amount": 40},
{"Name": "Peter Doe", "Amount": 10},
{"Name": "Lisa Doe", "Amount": 90},
{"Name": "John Doe", "Amount": 200}]
df = pd.DataFrame(my_list)
display(df.groupby('Name').sum())
Output Output
Amount
Name
John Doe 350
Lisa Doe 90
Peter Doe 50
Or you could do some dictionary manipulation:或者你可以做一些字典操作:
new_dict = {}
for e in my_list:
if e['Name'] not in new_dict.keys():
new_dict[e['Name']] = e['Amount']
else:
new_dict[e['Name']] += e['Amount']
my_list_2 = []
for k,v in new_dict.items():
my_list_2.append({'Name': k, 'Amount': v})
my_list_2
Output my_list_2
is Output
my_list_2
是
[{'Name': 'John Doe', 'Amount': 350},
{'Name': 'Peter Doe', 'Amount': 50},
{'Name': 'Lisa Doe', 'Amount': 90}]
Edit: Thank you @Nk03, to get the same output编辑:谢谢@Nk03,获得相同的 output
my_list_2 = df.groupby('Name' , as_index=False).sum().to_dict('records')
You can use itertools groupby
:您可以使用 itertools
groupby
:
from itertools import groupby
my_list_2 = [{'Name': g, 'Amount': sum(i['Amount'] for i in k)} for g, k in groupby(
sorted(my_list, key=lambda x: x['Name']), key=lambda x: x['Name'])]
OUTPUT
: OUTPUT
:
[{'Name': 'John Doe', 'Amount': 350},
{'Name': 'Lisa Doe', 'Amount': 90},
{'Name': 'Peter Doe', 'Amount': 50}]
Since you only want a sum for each name, I'd suggest a slightly different data structure for my_list_2
:由于您只想要每个名称的总和,因此我建议为
my_list_2
使用稍微不同的数据结构:
my_list_2 = {}
for entry in my_list:
name = entry["Name"]
amount = entry["Amount"]
my_list_2.setdefault(name, 0)
my_list_2[name] += amount
This iterates your original list entry by entry and cheks if the name is already known.这将逐个迭代您的原始列表条目,并检查名称是否已知。 If not, it sets it's sum to 0. Finally, the amount of the current entry is added to the current sum.
如果不是,则将其总和设置为 0。最后,将当前条目的数量添加到当前总和中。 In the end, you get a dict that looks like this:
最后,你会得到一个如下所示的 dict:
{'John Doe': 350, 'Peter Doe': 50, 'Lisa Doe': 90}
If you really want your old structure back, you can re-transform it using some list comprehension magic:如果你真的想要你的旧结构,你可以使用一些列表理解魔法重新转换它:
my_list_3 = [{"Name": name, "Amount": amount} for name, amount in my_list_2.items()]
However, if you have other data attached to your dicts, you might need to re-fetch it from your original list later.但是,如果您的 dicts 附加了其他数据,您可能需要稍后从原始列表中重新获取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.