0

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.values() = dic.values() + 1

didn't work, since we use the .values() function here. Is there a fast and simple way to modify every value of an dictionary in Python?

nieka
  • 259
  • 1
  • 4
  • 14

3 Answers3

3

Broadcasted addition cannot be applied to a list (or dict_values object).

Use a for loop instead to update the value at each key:

for k in dic:
    dic[k] += 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

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}
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
1

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. 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.

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.

SiHa
  • 7,830
  • 13
  • 34
  • 43