隔江千里
请看下面的代码:x = [ { 'acct': '2020', 'date': '2020-04-13', 'amount': 70.0, }, { 'acct': '2020', 'date': '2020-04-13', 'amount': 30.0, }, { 'acct': '2020', 'date': '2020-04-10', 'amount': 70.0, }, { 'acct': '2019', 'date': '2020-04-10', 'amount': 50.0, }]y = {}for i in x: if i["acct"] not in y: y[i["acct"]] = {i["date"]: i["amount"]} else: if i["date"] in y[i["acct"]]: y[i["acct"]][i["date"]] += i["amount"] else: y[i["acct"]].update({i["date"]: i["amount"]})print(y)输出:{ '2020': { '2020-04-13': 100.0, '2020-04-10': 70.0 }, '2019': { '2020-04-10': 50.0 }}
翻翻过去那场雪
您可以使用 pandas 对值进行分组并将值转换为dict. 迭代dict以获得最终输出list1 = [{ 'acct': '2020', 'date': '2020-04-13', 'amount': 70.0, },{ 'acct': '2020', 'date': '2020-04-13', 'amount': 30.0, },{ 'acct': '2020', 'date': '2020-04-10', 'amount': 70.0, },{ 'acct': '2019', 'date': '2020-04-10', 'amount': 50.0, }]import pandas as pddf = pd.DataFrame(list1)d = df.groupby(['acct','date']).sum().apply(list).to_dict()['amount']new_dict ={}for k,v in d.items(): if k[0] in new_dict: existing_dict = new_dict[k[0]] existing_dict.update({k[1]:v}) new_dict[k[0]] = existing_dict else: new_dict[k[0]]={k[1]:v}输出{'2019': {'2020-04-10': 50.0}, '2020': {'2020-04-10': 70.0, '2020-04-13': 100.0}}