使用从列表中添加其他值的函数更新字典

时间:2016-11-15 01:43:15

标签: python python-2.7 dictionary

function = ({"Books":10,"pens":20},[("Books",-5),("pens",-11),("pencils",3)])

目标:更新字典以输出:{“图书”:5,“笔”:9,“铅笔”:3}

for key,value in dicto.items():
        for item in mylist:
            if key == item[0]:
                dict[key] += item[1] 

为什么我的输出不包括铅笔键?

2 个答案:

答案 0 :(得分:3)

您正在迭代原始字典中的键,因此key永远不会等于铅笔。您应该迭代遍历列表中给出的键

>>> def f(D, L):
...     for k, v in L:
...         D[k] = D.get(k, 0) + v
...     return D
... 
>>> f({"Books":10,"pens":20},[("Books",-5),("pens",-11),("pencils",3)])
{'pencils': 3, 'Books': 5, 'pens': 9}

除了:

Counter类适用于此类事物

>>> from collections import Counter
>>> def f(D, L):
...     return Counter(D) + Counter(dict(L))
... 
>>> f({"Books":10,"pens":20},[("Books",-5),("pens",-11),("pencils",3)])
Counter({'pens': 9, 'Books': 5, 'pencils': 3})

答案 1 :(得分:0)

for key, value in mylist:
    dict[key] = dict.get(key, 0) + value
受AChampion的启发