Introduction to Python Dictionaries
Python Dictionaries
A dictionary is an unordered collection of key-value pairs.
It is also known as an associative array or hash table. Dictionaries are defined by enclosing the key-value pairs in curly braces {} or by using the dict() constructor.
Each key in a dictionary must be unique, and it is used to access its corresponding value.
Here's an example of a dictionary in Python:
person = {
"name": "John",
"age": 30,
"city": "New York"
}
Accessing Dictionary Values
You can access the value associated with a key in a dictionary by using the key inside square brackets [].
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print(person["name"])
print(person["age"])
Adding and Modifying Dictionary Elements
You can add a new key-value pair to a dictionary by assigning a value to a new or existing key.
person = {
"name": "John",
"age": 30,
"city": "New York"
}
person["occupation"] = "Engineer"
person["age"] = 31
print(person)
Dictionary Methods
Dictionaries have several built-in methods that you can use, such as keys(), values(), items(), get(), pop(), popitem(), clear(), update(), and more.
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print(person.keys())
print(person.values())
print(person.items())
print(person.get("name"))
print(person.pop("age"))
print(person)
person.clear()
print(person)
Checking Dictionary Membership
You can check if a key exists in a dictionary using the in operator. It returns True if the key is found in the dictionary and False otherwise.
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print("name" in person)
print("occupation" in person)