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