Python - Increment dictionary values

丶灬走出姿态 提交于 2019-12-25 08:18:04

问题


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


来源:https://stackoverflow.com/questions/40539411/python-increment-dictionary-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!