简体   繁体   English

如何在Python的字典的每个值中添加/减去一个整数?

[英]How can I add/substract an integer to every value of an dictionary in Python?

As the title indicates, i have a dictionary that looks like similar to this: 如标题所示,我有一本类似于此的字典:

dic = {0: 3.2, 1: 3.7, 2: 4.2, 3: 4.7, 4: 5.2, 5: 5.7}

I now want to add or substract an integer value to every value from the dic, but my simple attempt 我现在想向dic的每个值添加或减去一个整数值,但是我很简单

dic.values() = dic.values() + 1

didn't work, since we use the .values() function here. 没有用,因为我们在这里使用.values()函数。 Is there a fast and simple way to modify every value of an dictionary in Python? 是否有快速简便的方法来修改Python中字典的每个值?

Broadcasted addition cannot be applied to a list (or dict_values object). 广播加法不能应用于列表(或dict_values对象)。

Use a for loop instead to update the value at each key: 使用for循环来更新每个键上的值:

for k in dic:
    dic[k] += 1

You could just do, 你可以做,

for key in dic: dic[key] += 1

In [12]: dic
Out[12]: {0: 5.2, 1: 5.7, 2: 6.2, 3: 6.7, 4: 7.2, 5: 7.7}

Just for completeness, you could also use a dictionary comprehension: 仅出于完整性考虑,您还可以使用字典理解:

>>> dic = {0: 3.2, 1: 3.7, 2: 4.2, 3: 4.7, 4: 5.2, 5: 5.7}
>>> dic = {k:v+1 for k,v in dic.iteritems()}
>>> dic
{0: 4.2, 1: 4.7, 2: 5.2, 3: 5.7, 4: 6.2, 5: 6.7}

Note that I have used iteritems() , rather than items() , as it avoids creating in intermediate list. 请注意,我使用了iteritems()而不是items() ,因为它避免了在中间列表中创建。 Only really important if your dict is large, but I thought I'd mention it. 只有在您的字典很大的情况下才非常重要,但我想我会提一下。 Using iteritems is more similar to writing the for loop, in that we only iterate through the dict once. 使用iteritems与编写for循环更相似,因为我们只迭代一次dict。

See this answer for more detail on the difference between the two methods. 有关两种方法之间的区别的更多详细信息,请参见此答案。

Also note (as mentioned in the linked answer) that iteritems() is Python 2, for Python 3, items() returns a generator anyway. 还要注意(如链接的答案中所述) iteritems()是Python 2,对于Python 3, items()无论如何都会返回一个生成器。

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

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