Python iterate over dictionary
Loop over keys and values (order it's not guaranteed):
dict = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
# print key and values
for key, value in dict.items():
print('key: ', key, ' value: ', value)
result:
key: 0 value: None
key: 1 value: Python
key: 2 value: Java
key: 3 value: Javascriptt
Python loop over keys only
Loop over keys and values when the order doesn't matter:
dict = {1: 'Python', 2: 'Java', 3: 'Javascript'}
# print out all the keys
for key in dict:
print(key)
result:
1
2
3
Python loop over values only
Loop over keys and values when the order doesn't matter:
dict = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
# print out all values
for value in dict.values():
print(value)
result:
None
Python
Java
Javascript
Python other ways to loop
Dictionaries in python can be loop also with list(dict), dict.keys(), dict.values and dict.items:
dict = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
print(list(dict))
print(dict.keys())
print(dict.values())
print(dict.items())
result:
[0, 1, 2, 3]
dict_keys([0, 1, 2, 3])
dict_values(['None', 'Python', 'Java', 'Javascript'])
dict_items([(0, 'None'), (1, 'Python'), (2, 'Java'), (3, 'Javascript')])