python - 生成内置类型值的字典理解

标签 python python-2.7 dictionary dictionary-comprehension

我想做一个字典理解来获取一个键列表,其中内置类型 str 作为值。

headers = ['Header1', 'Header2', 'Header3']
print dict([(x,str) for x in headers])

输出:

{'Header2': <type 'str'>, 'Header3': <type 'str'>, 'Header1': <type 'str'>}

期望的输出:

{'Header2': str, 'Header3': str, 'Header1': str}

最佳答案

确实有一本内置 str 的字典在里面。

<type 'str'>是由于 print将使用通过调用对象的 __str__ 获得的值的调用当它打印它时。 str 的值是<type 'str'> .

如果您保存字典,访问其中一个成员并使用它,您会看到它 str类:

>>> d = dict([(x,str) for x in headers])
>>> d['Header1'](123)
'123'

关于python - 生成内置类型值的字典理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402938/

相关文章:

python - Elasticsearch不允许我添加较长的字典[TransportError(400)]

python - 如何向 discord.py 事件循环添加函数?

python - 如何在具有管理员权限的 Windows 7 上使用 Python 执行 cmd 命令

来自 fileconfig 的 Python 自定义日志处理程序

python - 将字典值导入到 Python 中的 OptionMenu 中

python - 数据框未在 Pycharm 中显示

python-2.7 - 使用SymPy加强对象属性之间的代数关系

ios - Here Map iOS Swift Crashed After call NMAApplicationContext.set(appId :. . appCode :. ..)

swift - 避免在 swift 中将字符串视为可选

python - 需要使用 GeoDjango 在 postGIS 上实现性能