9/4/26Less than 1 minuteAbout 146 words
Concept: Iterating over dictionaries
Iterating over a dictionary can be done using a for .. in loop. By default, the loop will iterate over the keys of the dictionary. However, you can also iterate over the values or key-value pairs using the values() and items() methods, respectively.
Iterating over keys
config = {
"hostname": "srv01.example.com",
"ip_address": "192.168.1.10",
"services": ["ssh", "http", "ssh"]
}
for key in config:
print(key, end=" ") # Output: hostname ip_address servicesIterating over values
config = {
"hostname": "srv01.example.com",
"ip_address": "192.168.1.10",
"services": ["ssh", "http", "ssh"]
}
for value in config.values():
print(value, end=" ") # Output: srv01.example.com 192.168.1.10 ['ssh', 'http', 'ssh']Iterating over key-value pairs
config = {
"hostname": "srv01.example.com",
"ip_address": "192.168.1.10",
"services": ["ssh", "http", "ssh"]
}
for key, value in config.items():
print(f"{key}: {value}", end=" ") # Output: hostname: srv01.example.com ip_address: 192.168.1.10 services: ['ssh', 'http', 'ssh']