我有一个字典,如:
{
"number_1":
{
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"number_2":
{
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"number_3":
{
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
"number_4":
{
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
}
我需要一种generic
的方式来获得值的总数如果字典对于键month_year
有相同的值那么例如对于month_year
5/2022
它将是:
{
"month_year": "5/2022",
"total_price": 2,
"total_average": 2,
"total_covered": 2,
}
我认为现有的答案要么太复杂,要么不够通用。这应该适用于所有新字段(假设它们仍然是数字),并依赖于内置的collections
来完成大部分繁重的工作。
from collections import defaultdict, Counter
def group(mappings):
dict_by_date = defaultdict(Counter)
for mapping in mappings.values():
date = mapping["month_year"]
fields = {k: v for k, v in mapping.items() if k != "month_year"}
dict_by_date[date].update(fields)
return [{"month_year": date, **fields} for date, fields in dict_by_date.items()]
示例的结果:
>>> from pprint import pprint
>>> pprint(group(test))
[{'average': 2, 'covered': 2, 'month_year': '5/2022', 'price': 2},
{'average': 186, 'covered': 200, 'month_year': '4/2022', 'price': 20}]
您可以将具有相同d['month_year']
值的所有元素d
分组,使用d['month_year']
作为键的dict
。
data = {
"number_1":
{"month_year": "5/2022", "price": 1, "average": 1, "covered": 1},
"number_2":
{"month_year": "5/2022", "price": 1, "average": 1, "covered": 1},
"number_3":
{"month_year": "4/2022", "price": 10, "average": 93, "covered": 100},
"number_4":
{"month_year": "4/2022", "price": 10, "average": 93, "covered": 100},
}
result = {}
for d in data.values():
if d['month_year'] in result:
for k in ('price', 'average', 'covered'):
result[d['month_year']][k] += d[k]
else:
result[d['month_year']] = dict(d)
print(result)
# {'5/2022': {'month_year': '5/2022', 'covered': 2, 'price': 2, 'average': 2},
# '4/2022': {'month_year': '4/2022', 'covered': 200, 'price': 20, 'average': 186}}
与您可能已经看到的其他答案一样,您的字典没有正确格式化。因为子字典在字典中,所以也必须给它们一个键。下面是一个例子:
{
"1st Dictionary": {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"2nd Dictionary": {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"3rd Dictionary": {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
"4th Dictionary": {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
}
这里你给每个子字典一个键。每个键简单地说明它是字典的字典中的哪个字典。下面是另一种方法:
{
0: {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
1: {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
2: {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
3: {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
}
这是一样的,除了你使用数字0-3。这可能是一个更好的主意,因为这样你就提供了一个类似于索引的键。
现在回到你的问题!如果希望获得这些字典中的任何一个的特定索引,首先必须使用所述字典定义一个变量,然后在变量旁边的括号内键入键(类似于列表)。为简单起见,我将使用第一本字典。这就是我要说的:dictionary={
"1st Dictionary": {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"2nd Dictionary": {
"month_year": "5/2022",
"price": 1,
"average": 1,
"covered": 1,
},
"3rd Dictionary": {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
"4th Dictionary": {
"month_year": "4/2022",
"price": 10,
"average": 93,
"covered": 100,
},
}
if dictionary["1st Dictionary"]["price"]>1:
print("if statement ran successfully!")
elif dictionary["1st Dictionary"]["price"]==1:
print("elif statement ran successfully!")
这里,输出是:elif语句运行成功!我们在这里做的是获取名为“1st Dictionary”
的键,然后在该字典中获取名为“price”
的键。下面是使用列表执行此行为的示例:
my_list=[
[1,2,3],
["a","b","c"],
[0.1,0.2,0.3]
]
if my_list[0][1]==2:
print("if statement ran successfully!")
如果我们运行这段代码,我们会得到输出:If语句运行成功!
这里我们检查my_list
内部第一个列表中的第二个索引是否等于2。说明一下,这里可以看到my_list
的第一个索引是[1,2,3]
,my_list
的第一个索引的第二个索引是2。
my_list[0]==[1,2,3]
my_list[0][1]==2
希望这回答了你的问题在一个简单易懂的方式!
您可以尝试下面的解决方案如果你有相似的相邻键,请尝试@steff solution
#假设你有一个字典列表,因为字典的集合是不可能的,因为不可哈希类型的字典
a = [{"month_year": "5/2022","price": 1,"average": 1,"covered": 1,
},{"month_year": "5/2022","price": 1,"average": 1,"covered": 1,},{"month_year": "4/2022","price": 10,"average": 93,"covered": 100,},{"month_year": "4/2022","price": 10,"average": 93,"covered": 100,},]
from itertools import groupby
from collections import Counter
a.sort(key=lambda x: x["month_year"]) # We need to do this because groupby needs data in sorted manner
print([ {**sum((Counter(vals) for vals in val if (_:=vals.pop("month_year")) and (not print(vals))), Counter()), **{"month_year": key}} for key, val in groupby(a, key=lambda x: x["month_year"])])
# output [{'price': 20, 'average': 186, 'covered': 200, 'month_year': '4/2022'}, {'price': 2, 'average': 2, 'covered': 2, 'month_year': '5/2022'}]
解释:首先使用键month_year
的groupby,我们得到唯一的键month_year和我们应用的组的值列表(使用Counter
的两个字典的和),然后把我的键放回生成的字典中。