简体   繁体   中英

Add iteration counter to dict/list comprehension python

I want to add an iteration counter to my list comprehension so that each key will have its own number based on which iteration we are on

currently:

itemdict = {item.name: [item.size, item.price] for item in items}

Which gives: {ItemNameExample: ['size=15', 'price=100']}

I want to do something like:

counter = 0
itemdict = {str(counter+=1) +'. '+ item.name: [item.size, item.price] for item in items}

Which would give me sometime like: {1. ItemNameExample: ['size=15', 'price=100']} {1. ItemNameExample: ['size=15', 'price=100']}

But the above code I tried always gives a 1 rather than adding to the count based on iteration

You could try it with enumerate :

itemdict = {str(i) + '. ' + item.name: [item.size, item.price]
            for i, item in enumerate(items, 1)}

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