Python - Increment dictionary values -
i have nested dictionary:
playlist = {u'user1': {u'roads': 1.0, u'pyramid song': 1.0, u'go alone': 1.0}} and i'm trying increment float values 1.0:
user = playlist.keys()[0] counts = playlist[user].values() c in counts: c += 1.0 i've come far.
now, how update dictionary incremented value?
to update float values in nested dictionary varying levels of nesting, need write recursive function walk through data structure, update values when floats or recall function when have dictionary:
def update_floats(d, value=0): 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 alone': 2.0, 'pyramid song': 2.0, 'roads': 2.0}}
Comments
Post a Comment