Вопрос

I want to turn a list ('a','b','c') into {'1':'a','2':'b','3':'c'}

 d = {key: value for key, value in targets}

returns keys as integer, I need it to be stored as a string so that I can append a string to each of the keys so that eventually I will end up with

{'column1','a','column2','b','column3'}
Это было полезно?

Решение

Just cast the key to str() and enumerate():

d = {str(i): value for i, value in enumerate(targets)}

or use formatting if you need to prepend the keys with a string:

d = {'column{}'.format(i): value for i, value in enumerate(targets)}

The key and value expressions in a dict comprehension are just that, python expressions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top