data_garden data_garden - 25 days ago 16
Python Question

Python - Increment dictionary values

I have this nested

dictionary
:

playlist = {u'user1': {u'Roads': 1.0, u'Pyramid Song': 1.0, u'Go It Alone': 1.0}}


and I'm trying write some code that increments its
float
value by
1.0


user = playlist.keys()[0]
counts = playlist[user].values()
for c in counts:
c += 1.0


I've come this far.

now, how do I
update
the
dictionary
with the
incremented value
?

Answer

To update float values in the nested dictionary with varying levels of nesting, you need to write a recursive function to walk through the data structure, update the values when they are floats or recall the function when you have a dictionary:

def update_floats(d, value=0):
    for i in d:
        if isinstance(d[i], dict):
            update_floats(d[i], value)
        elif isinstance(d[i], float):
            d[i] += value

update_floats(playlist, value=1)
print(playlist)
# {'user1': {'Go It Alone': 2.0, 'Pyramid Song': 2.0, 'Roads': 2.0}}
Comments