On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.
The normal case you enumerate the keys of the dictionary:
Use with AIexample_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
Use with AI0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
Use with AIfor i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
Use with AI0 1 a
1 2 b
2 3 c
3 4 d
Answer from João Almeida on Stack OverflowOn top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.
The normal case you enumerate the keys of the dictionary:
Use with AIexample_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
Use with AI0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
Use with AIfor i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
Use with AI0 1 a
1 2 b
2 3 c
3 4 d
The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():
Use with AIfor k, v in enumm.items():
print(k, v)
And the output should look like:
Use with AI0 1
1 2
2 3
4 4
5 5
6 6
7 7
how to loop through dict with enumerate and unpack the index, key, and value
python - How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration - Stack Overflow
python - Enumerate Dictionary Iterating Key and Value - Stack Overflow
python - Iterating over a dictionary using a 'for' loop, getting keys - Stack Overflow
an example of the dict
{10: {'total_power_usage': 152.1, 'total_pris': 336.62499999999994, 'huse_usage': 74.45588194444376, 'hus_pris': 195.42238509638779, 'charge_usage': 77.64411805555619, 'charge_price_full': 141.1951349036122, 'charge_price': 63.55101684805601}}now i can do :
for i, (k, v) in enumerate(my_result.items()):
print("index: {}, key: {}, value: {}".format(i, k, v))and that prints each line in the dict just fine. But how do i access each named element in the dict? if i need the value from 'total_pris' or 'charge_usage' ?
Instead of using mydict, you should be using mydict.items() with enumerate as:
for i, (k, v) in enumerate(mydict.items()):
# your stuff
Sample example:
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
print("index: {}, key: {}, value: {}".format(i, k, v))
# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b
Explanation:
enumerate()returns an iterator object which contains tuples in the format:[(index, list_element), ...]dict.items()returns an iterator object (in Python 3.x. It returnslistin Python 2.7) in the format:[(key, value), ...]- On combining together,
enumerate(dict.items())will return an iterator object containing tuples in the format:[(index, (key, value)), ...]
It's also possible to use itertools.count to count along.
from itertools import count
for i, (k, v) in zip(count(), mydict.items()):
# do something
This is useful especially if you want the counter to be fractional numbers. For example,
mydict = dict(zip(range(3), range(10, 13)))
for i, (k, v) in zip(count(step=0.5), mydict.items()):
print(f"index={i:<3}, key={k}, value={v}")
# index=0 , key=0, value=10
# index=0.5, key=1, value=11
# index=1.0, key=2, value=12
Given a dictionary d:
d
# {'A': 1, 'B': 2, 'C': 3, 'D': 4}
You can use a tuple to unpack the key-value pairs in the for loop header.
for i, (k, v) in enumerate(d.items()):
print(i, k, v)
# 0 A 1
# 1 B 2
# 2 C 3
# 3 D 4
To understand why the extra parens are needed, look at the raw output from enumerate:
list(enumerate(d.items()))
# [(0, ('A', 1)), (1, ('B', 2)), (2, ('C', 3)), (3, ('D', 4))]
The key-value pairs are packaged inside tuples, so they must be unpacked in the same way.
Assuming you just want to enumerate the key/value pairs (and don't need the index i), you can iterate d.items() directly:
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
for k, v in d.items():
print(k, v)
This prints something like
A 1
C 3
B 2
D 4
Note that entries are not necessarily ordered.
key is just a variable name.
Use with AIfor key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 3.x:
Use with AIfor key, value in d.items():
For Python 2.x:
Use with AIfor key, value in d.iteritems():
To test for yourself, change the word key to poop.
In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().
The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
Use with AIfor k in dict: ...which is equivalent to, but much faster than
Use with AIfor k in dict.keys(): ...as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
Use with AIfor key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...This means that
for x in dictis shorthand forfor x in dict.iterkeys().
In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.