python - python中字典迭代的问题

标签 python dictionary tuples iteration typeerror

我是 python 的新手,所以也许我的问题很容易解决。 我有一个字典组织如下: my_dict = {'x': (1.1, 3.4), 'y': (4.3, 7.5), 'z': (7.3, 9.5)}。 我想将每个值减少相同的数字,所以这就是我想要做的:

for k,v in my_dict.items():
    for a, b in v:
        a = a * 0.3
        b = b * 0.3 
        my_dict[k] = (a, b)
return my_dict

使用此代码时,我收到此错误:

for a, b in v:
TypeError: 'float' object is not iterable

所以看起来“for a, b in v”循环试图遍历 float,这是不可能的。 因此,我尝试在 for 循环中打印 my_dict.items() 和 k,v,以查看 for 循环迭代的是什么,这就是我得到的:

for k,v in my_dict.items():
    print my_dict.items()
    print k,v

[('x', (1.1, 3.4)), ('y', (4.3, 7.5)), ('z', (7.3, 9.5))]
y (4.3, 7.5)

我可以看到两个奇怪的东西: - 我期待“print k,v”命令打印每个键、值对,但我只得到 y 键及其值 - 通过查看 my_dict.items(),在我看来 v 不是 float ,而是包含两个 float 的元组。那么为什么会出现 float object is not iterable 错误呢?

非常感谢任何帮助。 再次,如果这是一个愚蠢的问题,我很抱歉,但我刚开始使用 python,我被这个问题困住了。

谢谢!

最佳答案

你可以在这里使用字典理解

>>> {k: tuple(i * 0.3 for i in v) for k, v in my_dict.items()}
{'x': (0.33, 1.02), 'y': (1.2899999999999998, 2.25), 'z': (2.19, 2.85)}

关于python - python中字典迭代的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997751/

相关文章:

python - Numpy 数组,数据必须是一维的

python - 如何将 Python.h 库添加到 Eclipse 以在 C++ 程序中使用?

python - 在 Python 中将元组元素附加到元组的元组中

python - 如何在 Python 中将元组中一项的值分配给另一项?

python - Pandas:应用函数:TypeError:不支持的操作数类型 -: 'unicode' 和 'unicode'

python - 如何解析 "UTC+01:00"格式的时区

c# - 将动态类型转换为字典 C#

c# - 带有可选键的多键字典

c# - 填充字典中出现 KeyNotFoundException

tuples - 如何迭代 Julia NamedTuple 中的名称和值?