user2242044 user2242044 - 4 months ago 8
Python Question

Dictionary Comprehension to generate values of built-in type

I would like to do a dictionary comprehension to get a list of keys with the built-in type of

str
as values.

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


output:

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


Desired output:

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

Jim Jim
Answer

You do have a dictionary with str in it.

The <type 'str'> is due to the print call which will use the value obtained from calling an objects' __str__ when it prints it. That value for str is <type 'str'>

If you save the dictionary, access one of the members and use it you'll see it is the str class:

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