Thursday, November 28, 2024
Google search engine
HomeLanguagesPython Dictionary with For Loop

Python Dictionary with For Loop

Combining dictionaries with for loops can be incredibly useful, allowing you to iterate over the keys, values, or both. In this article, we’ll explore Python dictionaries and how to work with them using for loops in Python.

Understanding Python Dictionaries

In this example, a person is a dictionary with three key-value pairs. The keys are “name,” “age,” and “city,” and the corresponding values are “John,” 30, and “New York,” respectively.

Python3




person = {"name": "John", "age": 30, "city": "New York"}
print(person)


Modifying Dictionary Elements While Iterating

Be cautious when modifying dictionary elements while iterating over them, as it can lead to unexpected results. If you need to make changes to the dictionary, consider creating a copy or collecting the changes in a separate list or dictionary.

  • Iterating Over Dictionary Keys
  • Iterating Over Dictionary Values
  • Iterating Over Both Keys and Values

Iterating Over Dictionary Keys

In this code, we use the keys() method to obtain a view of the dictionary’s keys, and then we iterate over these keys using a for loop.

Python3




# Iterating over dictionary keys
person = {"name": "John", "age": 30, "city": "New York"}
for key in person.keys():
    print(key)


Output

name
age
city

Iterating Over Dictionary Values

If you want to iterate over the values in a dictionary, you can use the values() method. Here’s how you can do it:

Python3




# Iterating over dictionary values
person = {"name": "John", "age": 30, "city": "New York"}
for value in person.values():
    print(value)


Output

John
30
New York

Iterating Over Both Keys and Values

Sometimes, you may need to iterate over both the keys and values simultaneously. To do this, you can use the items() method, which returns a list of key-value pairs as tuples.

Python3




# Iterating over dictionary key-value pairs
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
    print(key, ":", value)


Output

name : John
age : 30
city : New York

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments