【发布时间】:2021-09-15 10:20:27
【问题描述】:
我如何对 literals 或 list 的值使用字典理解
现在我可以遍历嵌套字典并获得带有嵌套值的结果字典,但我想在输出中包含dict、列表和文字(int、str)
这是我的例子(我知道这里不需要isinstance)
nested_dict = {'first':{'a':1}, 'second':{'b':2}, 'third': 3, 'fourth': [1, 2, 3, 4]}
float_dict = {
outer_k: { float(inner_v)
for (inner_k, inner_v) in outer_v.items()}
for (outer_k, outer_v) in nested_dict.items()
if isinstance(outer_v, dict)
}
print(float_dict)
预期输出:
{'first': {'a': 1.0}, 'second': {'b': 2.0}, 'third': 3.0, 'fourth': [1.0, 2.0, 3.0, 4.0]}
【问题讨论】:
-
想要的输出是什么?
-
同一个字典,但只有每个值都转换为浮点数
-
你的意思是
third和fourth键也变成了浮点数? -
是的,准确的...
-
如果输入不统一,你就不能真正做到(合理地)用一个单一的理解。您将需要一个递归函数,它专门检查它是否在处理列表、字典或单个值,并相应地处理它们(递归地)。例如:stackoverflow.com/q/55704719/476
标签: python dictionary