Python - Increment dictionary values

2019-09-06 09:36发布

问题:

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 to increment its float values 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?

回答1:

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


回答2:

If the playlist dictionary is only nested one level deep, you can use the following snippet:

for user_key in playlist.keys():
    for song_key in playlist[user_key].keys():
        playlist[user_key][song_key] += 1