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:
example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
0 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:
example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
0 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():
for k, v in enumm.items():
print(k, v)
And the output should look like:
0 1
1 2
2 3
4 4
5 5
6 6
7 7
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' ?