在使用dict.values()或dict.itervalues()进行迭代时修改字典值 [英] Modifying dictionary values while iterating with dict.values() or dict.itervalues()

查看:142
本文介绍了在使用dict.values()或dict.itervalues()进行迭代时修改字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样初始化的字典:

I have a dicionary that is initialized like so:

tab = {'Mike': 0, 'Chad': 15, 'Taylor': 2}

我希望能够将整数添加到字典中的每个值.
例如,添加5后,字典应如下所示:

I want to be able to add integers to each value in the dictionary.
For example, after adding 5, the dictionary should look like this:

{'Mike': 5, 'Chad': 20, 'Taylor': 7}

这似乎可以用几行代码来完成,但我无法弄清楚. 我已经尝试过for循环:

It seems as if this can be done with a couple of lines of code but I can't figure it out. I've tried a for loop:

for k in tab.itervalues():
    k = k + 5

我运行以下代码,然后打印出字典:

I run this code and then print out the dictionary:

tab = {'Mike': 0, 'Chad': 15, 'Taylor': 2}

字典没有变化.我不确定Python是否将值识别为字符串或整数.

The dictionary has undergone no change. I'm not sure if Python recognizes the values as strings or integers.

推荐答案

最简单的方法?

for k in tab.keys():
    tab[k] += 5

这篇关于在使用dict.values()或dict.itervalues()进行迭代时修改字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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