Skip to content

Python Dictionary

Dictionaries in Python Explanation

In Python, a dictionary is a collection of key-value pairs, where each key must be unique. Dictionaries are defined by enclosing key-value pairs in curly braces {} and separating them with commas. Dictionaries are useful for mapping values to unique identifiers.

Example:

        
# Creating a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}

# Accessing values
name = person["name"]
age = person["age"]

# Modifying values
person["age"] = 31

# Adding new key-value pairs
person["gender"] = "Female"

# Dictionary methods
keys = person.keys()
values = person.values()
        
    

In the example above, person is a dictionary with keys like "name," "age," and "city," each associated with corresponding values. You can access, modify, and add key-value pairs in a dictionary.