我想做一个字典理解来获取一个键列表,其中内置类型 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/