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 to increment its float values by 1.0: user = pla
Solution 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:
defupdate_floats(d, value=0):
for i in d:
ifisinstance(d[i], dict):
update_floats(d[i], value)
elifisinstance(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}}
Solution 2:
If the playlist dictionary is only nested one level deep, you can use the following snippet:
foruser_keyin playlist.keys():
forsong_keyin playlist[user_key].keys():
playlist[user_key][song_key] += 1
Post a Comment for "Python - Increment Dictionary Values"