Reputation: 1390
If I have a list of dictionaries, is there a way to refer to a specific element within the for loop declaration?
Something like this:
dict_lst = [
{'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 2, 'c': 3},
]
for d['a'] as dict_elem in dict_lst:
print dict_elem
Or something similar?
Upvotes: 0
Views: 139
Reputation: 4501
you can use this:
for element in dict_lst:
print element['some_key']
Upvotes: 0
Reputation: 4058
This is one of the fastest and Pythonic methods to do it, lean on Python 3:
for key, val in d.iteritems():
print key, val
There is also a similar method items
which does almost the same. items
will create a list of tuples with key and value if you call it in the for
loop statement. There is also a similar method keys
which only returns you a list of keys.
iteritems
will not generate a list of tuples when you call it in the for loop. Each element will be evaluated in each loop cycle. So there is no initial overhead and extensive memory usage. If you break the loop it's better as well.
Upvotes: 0
Reputation: 365835
No, there's no as
clause in for
statements.
But it's pretty easy to do this explicitly:
for d in dict_lst:
dict_elem = d['a']
print dict_elem
Or, more simply:
for d in dict_list:
print d['a']
Or, if you want to get fancy:
for dict_elem in (d['a'] for d in dict_lst):
print dict_elem
Or, just for fun:
for dict_elem in map(operator.itemgetter('a'), dict_lst):
print dict_elem
Which you can wrap up as a reusable function:
def itemmap(dicts, key):
for item in dicts:
yield item[key]
for dict_elem in itemmap(dict_lst, 'a'):
print dict_elem
As a side note, you actually can do for d['a'] in dict_list:
, but that just reassigns d['a']
(assuming d
is already a dictionary) to each new dictionary in the list, which is usually a confusing thing to do. (It can be useful for obfuscated code contests…)
Upvotes: 3
Reputation:
You can use a generator expression like so:
>>> dict_lst = [
... {'a': 1, 'b': 2, 'c': 3},
... {'a': 1, 'b': 2, 'c': 3},
... {'a': 1, 'b': 2, 'c': 3},
... ]
>>> for dict_elem in (d['a'] for d in dict_lst):
... dict_elem
...
1
1
1
>>>
Upvotes: 2