The list data type is easy to iterate by using for item in items
where item is the object in the list -
items
.
Suppose to iterate through datas within a dictionary, using this as the dictionary:
example = {
'object_name': 'linux',
'address': '192.168.1.100',
'mask': '255.255.255.0',
'gateway': '192.168.1.1',
'prefix': '24'
}
Returns both the keys and values
Use the for loop to iterate and get the keys and values of the dictionary, and the return value is a tuple.
# returns tuple, example.items return both the keys and values.
for i in example.items():
print(i)
Another way to do it, the return will not be a tuple:
for key, value in example.items():
print(key + " " + value)
Returns only the keys
Use the for loop to enumerate only the keys.
# return only keys.
for i in example.keys():
print(i)
another way to do it:
for key, _ in example.items():
print(key)
Returns only the values
Iterate over the dictionary and returns only values.
# return only values.
for i in example.values():
print(i)
another way to do it:
for _, value in example.items():
print(value)