Sunday, April 20, 2025

Python Dictionary Iteration

To grab only keys from dictionary use key() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.keys():
    print("Key: ", x)

Result: 


Key:  Color 1
Key:  Color 2
>>> 

Same approach for values, using value() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.values():
    print("Value: ", x)

Result:  


Value:  Red
Value:  Yellow
>>> 

Or use items() function to grab key-value pairs:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

print("Key -> Value")
print("-" * 49)

for x, y in colors.items():
    print(x, " -> ", y)

Result:  


Key -> Value
-------------------------------
Color 1  ->  Red
Color 2  ->  Yellow
>>> 

This is how to extract keys and values into dedicated lists:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x in colors.keys():
    key_parts.append(x)

for y in colors.values():
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Same as above, using only one for loop:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x, y in colors.items():
    key_parts.append(x)
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Excellent. In next tutorial we will learn about functions.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...