data_garden data_garden - 1 year ago 136
Python Question

Python - Increment dictionary values

I have this nested


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
value by

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

I've come this far.

now, how do I
with the
incremented value

Answer Source

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)
# {'user1': {'Go It Alone': 2.0, 'Pyramid Song': 2.0, 'Roads': 2.0}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download