Home HTML CSS JAVASCRIPT BOOTSTRAP Python Docker ML tutorial About us Privacy policy

Python Dictionaries

Python Dictionaries - CodesFamily

Python Dictionaries

Dictionaries in Python are used to store data in key-value pairs. They provide fast lookup and modification capabilities.

Creating a Dictionary


# Creating a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
        

Accessing Dictionary Values


# Accessing values
print(person["name"])  # Output: Alice
print(person.get("age"))  # Output: 25
        

Modifying a Dictionary


# Modifying values
person["age"] = 26
person["country"] = "USA"  # Adding a new key-value pair
print(person)
        

Removing Items


# Removing a key-value pair
del person["city"]
person.pop("age")
print(person)
        

Looping Through a Dictionary


# Looping through dictionary
for key, value in person.items():
    print(f"{key}: {value}")
        

Dictionary Methods


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

print(keys)
print(values)
print(items)
        

Nested Dictionaries


# Nested dictionary
dept = {
    "HR": {"employees": 5, "head": "John"},
    "IT": {"employees": 10, "head": "Alice"}
}
print(dept["IT"]["head"])  # Output: Alice
        

Conclusion

Python dictionaries are powerful for data storage and retrieval. They are widely used in real-world applications like data manipulation and APIs.