简体   繁体   English

Python字典:将满足给定条件的值加到键的总和中

[英]Python dictionary: Add to the key sum of values fulfilling given condition

I've following nested dictionary, where the first number is resource ID (the total number of IDs is greater than 100 000): 我遵循的是嵌套字典,其中第一个数字是资源ID(ID的总数大于100 000):

dict = {1: {'age':1,'cost':14,'score':0.3},
        2: {'age':1,'cost':9,'score':0.5},
        ...}

I want to add to each resource a sum of costs of resources with lower score than given resource. 我想向每种资源添加总成本低于给定资源的资源成本总和。 I can add 'sum_cost' key which is equal to 0 by following code: 我可以通过以下代码添加等于0的'sum_cost'键:

for id in adic:
    dict[id]['sum_cost'] = 0

It gives me following: 它给我以下内容:

dict = {1: {'age':1,'cost':14,'score':0.3, 'sum_cost':0},
        2: {'age':1,'cost':9,'score':0.5,'sum_cost':0},
        ...}

Now I would like to use ideally for loop (to make the code easily readable) to assign to each sum_cost a value equal of sum of cost of IDs with lower score than the given ID. 现在,我想理想地使用for循环(以使代码易于阅读)为每个sum_cost分配一个值,该值等于比给定ID得分低的ID的成本之和。

Ideal output looks like dictionary where 'sum_cost' of each ID is equal to the cost of IDs with lower score than given ID: 理想的输出看起来像字典,其中每个ID的“ sum_cost”等于得分低于给定ID的ID的成本:

dict = {1: {'age':1,'cost':14,'score':0.3, 'sum_cost':0},
        2: {'age':1,'cost':9,'score':0.5,'sum_cost':21},
        3: {'age':13,'cost':7,'score':0.4,'sum_cost':14}}

Is there any way how to do it? 有什么办法吗?

Notes: 笔记:

Using sorted method for sorting the dictionary output corresponding to the key score 使用排序方法对与关键score对应的字典输出进行排序

dictionary get method to get dictionary values dictionary get方法获取字典值

and using a temporary variable for cumulative addition os sum_cost 并使用临时变量进行累加os sum_cost

Code: 码:

dicts = {1: {'age': 1, 'cost': 14, 'score': 0.3, 'sum_cost': 0},
         2: {'age': 1, 'cost': 9, 'score': 0.5, 'sum_cost': 0},
         3: {'age': 13, 'cost': 7, 'score': 0.4, 'sum_cost': 0}}

sum_addition = 0

for key, values in sorted(dicts.items(), key=lambda x: x[1].get('score', None)):
    if dicts[key].get('score') is not None: #By default gives None when key is not available
        dicts[key]['sum_cost'] = sum_addition
        sum_addition += dicts[key]['cost']
        print key, dicts[key]

A even more simplified method by @BernarditoLuis and @Kevin Guan advise @BernarditoLuis和@Kevin Guan提出的甚至更简化的方法建议

Code2: 代码2:

dicts = {1: {'age': 1, 'cost': 14, 'score': 0.3, 'sum_cost': 0},
         2: {'age': 1, 'cost': 9, 'score': 0.5, 'sum_cost': 0},
         3: {'age': 13, 'cost': 7, 'score': 0.4, 'sum_cost': 0}}

sum_addition = 0

for key, values in sorted(dicts.items(), key=lambda x: x[1].get('score', None)):
    if dicts[key].get('score'): #By default gives None when key is not available
        dicts[key]['sum_cost'] = sum_addition
        sum_addition += dicts[key]['cost']
        print key, dicts[key]

Output: 输出:

1 {'sum_cost': 0, 'age': 1, 'cost': 14, 'score': 0.3}
3 {'sum_cost': 14, 'age': 13, 'cost': 7, 'score': 0.4}
2 {'sum_cost': 21, 'age': 1, 'cost': 9, 'score': 0.5}

What about using OrderedDict? 怎样使用OrderedDict?

from collections import OrderedDict

origin_dict = {
    1: {'age':1,'cost':14,'score':0.3}, 
    2: {'age':1,'cost':9,'score':0.5}, 
    3: {'age':1,'cost':8,'score':0.45}
}
# sort by score
sorted_dict = OrderedDict(sorted(origin_dict.items(), key=lambda x: x[1]['score']))
# now all you have to do is to count sum_cost successively starting from 0
sum_cost = 0
for key, value in sorted_dict.items():
    value['sum_cost'] = sum_cost
    sum_cost += value['cost']

print sorted_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM