Python-递增字典值 [英] Python - Increment dictionary values

查看:316
本文介绍了Python-递增字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个嵌套的dictionary:

 playlist =  {u'user1': {u'Roads': 1.0, u'Pyramid Song': 1.0, u'Go It Alone': 1.0}}

,并且我尝试将其float值增加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

我走了这么远.

现在,我如何用incremented value update dictionary?

推荐答案

要使用不同的嵌套级别更新嵌套字典中的float值,您需要编写一个递归函数来遍历数据结构,并在它们出现时更新值是浮点型的,或者在有字典时调用该函数:

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

这篇关于Python-递增字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆