简体   繁体   中英

Python simultaneously loop, enumerate, and add to a dictionary

Is there a neat way to loop through a list, adding the value as a dictionary key, and its position in the list as its value? something like:

for x,y in enumerate(line):
    dictItem[x] = y

but in one line?

You can simply feed the enumerate to the dict constructor:

dictItem = dict(enumerate(line))

dict(..) can construct a dictionary when you give it an iterable of 2-tuples that contain the key and the value . Your enumerate(..) generates tuples with that key and value.

In case you want to update the dictionary (ie add new values or update the existing ones), you can write:

dictItem.update(enumerate(line))

You can try:

dictItem.update(enumerate(line))

For example:

>>> a = {}
>>> a.update(enumerate([4, 5, 6]))
>>> a
{0: 4, 1: 5, 2: 6}

Try this,

{pos:val for pos,val in enumerate(line)}

Exicution,

In [6]: line = [7,6,5,4,4]    
In [7]: {pos:val for pos,val in enumerate(line)}
Out[7]: {0: 7, 1: 6, 2: 5, 3: 4, 4: 4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM