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

时间:2015-11-03 09:16:07

标签: python python-3.x dictionary sum

我跟随嵌套字典,其中第一个数字是资源ID(ID的总数大于100 000):

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

我想向每个资源添加一个资源成本总和,其得分低于给定资源。我可以添加' sum_cost'通过以下代码等于0的键:

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

它给了我以下信息:

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

现在我想理想地使用循环(以使代码易于阅读)为每个sum_cost分配一个等于ID成本之和的值,其得分低于给定ID。

理想输出看起来像字典,其中sum_cost'每个ID的数量等于分数低于给定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}}

有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:4)

备注:

使用sorted method对与键score

对应的字典输出进行排序

dictionary get method 获取字典值

并使用临时变量进行累积加法os sum_cost

<强>代码:

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]

@BernarditoLuis和@Kevin Guan建议的更简化的方法

<强>代码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]

<强>输出:

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}

答案 1 :(得分:1)

使用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