Skip to content

Example for key value in dict Python

  • by

For loop will iterate through a dictionary to get key values in Python. In dictionary iterates over all the keys and helps us to access the key-value pair one after the other in the loop

Iterate Through a Dictionary in Python

A simple example code gets the key value of dict using for loop in Python. In the loop, you will get keys and use those keys in the get method to get the value for this key.

dict1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}

for key in dict1:
    print(key, dict1.get(key))


Example for key value in dict Python

More examples of how to use key-value pairs in a Python dictionary:

# Define a dictionary with key-value pairs
person = {"name": "Alice", "age": 25, "city": "New York"}

# Access the value associated with a key
print(person["name"]) # Output: "Alice"

# Change the value associated with a key
person["age"] = 26

# Add a new key-value pair to the dictionary
person["email"] = "[email protected]"

# Remove a key-value pair from the dictionary
del person["city"]

# Iterate over the key-value pairs in the dictionary
for key, value in person.items():
    print(f"{key}: {value}")

Do comment if you have any doubts or suggestions on this Python dict topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *