Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a for loop in which I use the iterator always in the same manner, like this

for dict in mylist:
    var = dict['prop']
    var2 = f( dict['prop'] )
    ...

This is clumsy. The only alternatives I can think of:

  • local variable
  • wrapping the mylist in a list comprehension. But that seems overkill and is probably inefficient

Any better way?

share|improve this question
    
I don't see any problems with that, although I'd write it as var, var2 = dict['prop'], f(dict['prop']) –  vaultah 1 hour ago
    
To be honest, I am not seeing the clumsiness (except the unnecessary second lookup of dict['prop']). Perhaps show us more of your code? –  NPE 1 hour ago
    
for dict_prop=dict['prop'] in mylist: ... would seem more natural for me. Just looking if I missed some python feature –  Basti 1 hour ago

1 Answer 1

I'm not sure if this is prettier but you can construct a generator in for loop definition:

>>> a = [{'prop': 1}, {'prop': 2}]
>>> for x in (x['prop'] for x in a):
...     print(x)
... 
1
2

Or use operator.itemgetter and map:

>>> from operator import itemgetter
>>> for x in map(itemgetter('prop'), a):
...     print(x)
... 
1
2

This won't make extra dictionary lookups and starting from Python 3 map is as efficient as a generator.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.