0

Say I had a dictionary, containing float values and I wanted to add a specific float such as 0.1 to each value in the dictionary, how would I go about doing this

{1:0.1, 2:0.2, 3:0.3}

I would want the new dictionary to be

{1:0.2, 2:0.3, 3:0.4}

I know how to do this with a list but I have no clue how to do it with a dictionary

3 Answers3

2

You can use a dict comprehension. Basically iterate over the items and add 0.1 to each value.

data = {1:0.1, 2:0.2, 3:0.3}
data = {key: value + 0.1 for key, value in data.items()}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

The two current answers are fine, but both create a new dictionary.

Of course, you could always update your existing dictionary (e.g. named d):

for k in d: 
    d[k] += 0.1

Which (for clarity) is the same as (explicit .keys()):

for k in d.keys(): 
    d[k] += 0.1

Note that this will not work or do what you expect:

for v in d.values(): 
    v += 0.1
jedwards
  • 29,432
  • 3
  • 65
  • 92
0

You can use a dictionary comprehension:

data = {1:0.1, 2:0.2, 3:0.3}

result = {k: v + 0.1 for k, v in data.items()}
print(result)

This prints:

{1: 0.2, 2: 0.30000000000000004, 3: 0.4}

which contains some (unavoidable) floating point rounding error.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33