将不同字典中相同键的值添加到列表中

时间:2021-06-03 12:36:37

标签: python list dictionary for-loop

我有一个字典列表:

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},]

如果值相同,我想遍历字典列表并为键“Name”找到相同的值,我想添加“Amounts”并将其保存到新字典中。例如,上面的列表应该变成:

my_list_2 = [
{"Name": "John Doe", "Amount": 350},
{"Name": "Peter Doe", "Amount": 50},
{"Name": "Lisa Doe", "Amount": 90},]

有人可以建议任何 Pythonic 的方法吗?

非常感谢!

3 个答案:

答案 0 :(得分:1)

您是否愿意使用数据框来完成此任务?

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())

输出

            Amount
    Name    
John Doe    350
Lisa Doe    90
Peter Doe   50

或者你可以做一些字典操作:

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

输出 my_list_2

[{'Name': 'John Doe', 'Amount': 350},
 {'Name': 'Peter Doe', 'Amount': 50},
 {'Name': 'Lisa Doe', 'Amount': 90}]

编辑:谢谢@Nk03,以获得相同的输出

my_list_2 = df.groupby('Name' , as_index=False).sum().to_dict('records')

答案 1 :(得分:1)

您可以使用迭代工具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

[{'Name': 'John Doe', 'Amount': 350},
 {'Name': 'Lisa Doe', 'Amount': 90},
 {'Name': 'Peter Doe', 'Amount': 50}]

答案 2 :(得分:1)

由于您只需要每个名称的总和,我建议 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

这将逐项迭代您的原始列表条目,并检查名称是否已知。如果不是,则将其总和设置为 0。最后,将当前条目的数量添加到当前总和中。最后,你会得到一个看起来像这样的字典:

{'John Doe': 350, 'Peter Doe': 50, 'Lisa Doe': 90}

如果你真的想要你的旧结构,你可以使用一些列表理解魔法重新转换它:

my_list_3 = [{"Name": name, "Amount": amount} for name, amount in my_list_2.items()]

但是,如果您有其他数据附加到您的 dicts,您可能需要稍后从原始列表中重新获取它。