6.0 Python: Loop Dictionaries
6.1 Loop Through a Dictionary
You can loop through a dictionary by using a for
loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
6.1.1 Example
Print all key names in the dictionary, one by one:
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for k in microsoft:
print(k)
6.1.2 Example
Print all values in the dictionary, one by one:
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for k in microsoft:
print(microsoft[k])
6.1.3 Example
You can also use the values()
method to return values of a dictionary:
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for v in microsoft.values():
print(v)
6.1.4 Example
You can use the keys()
method to return the keys of a dictionary:
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for k in microsoft.keys():
print(k)
6.1.5 Example
Loop through both keys and values, by using the items()
method:
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for k, v in microsoft.items():
print(k, v)
microsoft = {
"upn": "trustinveritas",
"type": "hacker",
"year": "1991",
"skills": ["C++", "C#", ".NET", "Rust", "Python", "PowerShell"]
}
for k, v in microsoft.items():
if isinstance(v, list):
print(f"The key '{k}' has the values '{v}'.")
else:
print(f"The key '{k}' has the value '{v}'.")