尝试通过字典理解将字典中的所有值转换为 int

Trying to convert all values in a dictionary to int through dictionary comprehension

我有这样的字典:

{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'}

并且我想尽可能通过字典理解将所有值转换为整数。所以我想要这个:

{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: 'pythonic'}

我试过了:

{i: int(m[i]) for i in m if type(m[i]) == str and m[i].isdigit()}

但它只包括那些可以转换为整数的字符串值。我也试过把整个东西放在 try catch 中,但它不起作用

我知道这可以通过一个简单的 for 循环来完成,但是还有其他方法吗?

通过将 if 添加到循环的末尾,您正在 过滤,将输出限制为键值对,其中值是一个字符串并且包含位数。

改为在值表达式中使用条件表达式;这样你就可以保留 all 键值对,但只将 int() 应用于这很重要的值,并将其余值保持不变:

{k: int(v) if isinstance(v, str) and v.isdigit() else v for k, v in m.items()}

而不是仅仅遍历 m(并且只获取键),我使用 dict.items() 一步获取键和相应的值。

{k: int(v) if str(v).isdigit() else v for k, v in m.items()}