繁体   English   中英

将列表中的元素添加到字典中并增加值

[英]Add element from list to dictionary and increase value

我有字典和清单。 列表仅包含项目,字典包含项目以及我拥有多少个给定项目。 我想做的是遍历字典和列表,如果字典中的键与列表中的项目相同,我只想将其值更新1,但是如果没有相同的项目将项目表单列表添加到dict并将其值设置为1。

stock = {apple: 1, banana: 4, orange: 10}
delivery = [apple, apple, grapefruit]

    for k, v in stock.items():
        for item in delivery:
            if item == stock[k]:
                stock[v] += 1
        else:
            stock.update({item:1})

输出应如下所示:

stock = {apple: 3, banana: 4, orange: 10, grapefruit: 1}

但是我收到消息:字典在迭代过程中更改了大小

在迭代dictlist时,您不应更改它。 您可以像这样编写代码:

stock = {'apple': 1, 'banana': 4, 'orange': 10}
delivery = ['apple', 'apple', 'grapefruit']

for item in delivery:
    if item in stock:
        stock[item] +=1
    else:
        stock[item] = 1

print(stock)

实际上,您可以使用collections中的Counter来实现您想要的功能。

from collections import Counter
stock = Counter({'apple': 1, 'banana': 4, 'orange': 10})
delivery = ['apple', 'apple', 'grapefruit']
stock.update(delivery)

使用dict.get()

stock = {'apple': 1, 'banana': 4, 'orange': 10}
delivery = ['apple', 'apple', 'grapefruit']

for d in delivery:
    stock[d] = stock.get(d, 0) + 1

print(stock)

输出:

{'apple': 3, 'banana': 4, 'orange': 10, 'grapefruit': 1}

您可能需要反转枚举的顺序并遍历列表,将项目添加到dict或将它们的值增加一(如适用):

for item in delivery:
    if item in stock:
        stock[item] += 1
    else:
        stock[item] = 1

(请注意,您也可以将defaultdict(int)用作“ stock”字典对象,因此您甚至不需要if / else并可以执行以下操作:

for item in delivery:
    stock[item] += 1

在这种情况下,最好的方法是使用Counter集合而不是标准字典( https://docs.python.org/2/library/collections.html )看看那里给出的基本示例:

# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1

使用标准字典时,可以遍历列表并遵循以下几行:

for v in delivery:
    try:
        stock[v] += 1
    except KeyError:
        stock[v] = 1

或者,您可以使用dict的* get *方法并测试None。

您可以为此使用collections.counter

from collections import Counter
stock = Counter({'apple': 1, 'banana': 4, 'orange': 10})
delivery = ['apple', 'apple', 'grapefruit']
stock.update(delivery)

stock
# Counter({'orange': 10, 'banana': 4, 'apple': 3, 'grapefruit': 1})

也可能是这样的:

stock = {'apple': 1, 'banana': 4, 'orange': 10}
delivery = ['apple', 'apple', 'grapefruit']

stock.update({item: delivery.count(item) + stock.get(item,0) 
               for item in set(delivery)}) 

print(stock)
# {'apple': 3, 'banana': 4, 'orange': 10, 'grapefruit': 1})

暂无
暂无

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

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