A dictionary in Python is an unordered collection of key-value pairs. Each item in the dictionary has a key, and each key maps to a unique value.
Dictionary
student = {
"name": "John Doe",
"age": 20,
"grade": "Sophomore"
}
"name"
, "age"
, and "grade"
are keys, and "John Doe"
, 20
, and "Sophomore"
are their respective values.
Key Characteristics
- Unordered: Dictionaries are unordered, meaning the items do not have a defined order. The order of items can change over time, making the index of each item unreliable.
- Mutable: Dictionaries are mutable. This means you can change, add, and remove items after the dictionary is created.
- Indexed by Keys: Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys. This key-value pair system makes dictionaries incredibly versatile for storing and organizing data.
- Cannot Contain Duplicate Keys: Each key in a dictionary must be unique. If a duplicate key is assigned a value, the original key’s value will be overwritten.
Dictionary Creation
Dictionaries are created by enclosing key-value pairs in curly braces {}
.
A colon :
separates keys from its associate value.
person = {"name": "Alice", "age": 25}
Accessing Elements
print(person["name"]) # Output: Alice
Modifying Elements
Dictionaries are mutable. You can change the value of a specific item by referring to its key.
Dictionaries are mutable. You can change the value of a specific item by referring to its key.
Adding Elements
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
person["city"] = "New York"
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Removing Elements
Use the del
statement.
del person["age"]
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
Making a copy
Use the copy
keyword
y = x.copy()
print(y) # Output: {'one': 'uno', 'two': 2, 'three': 3}
Removing all items
Use the clear
keyword
x.clear()
print(x) # Output: {}
Getting the Number of Items
Use the len()
keyword
x.clear()
print(x) # Output: {}
Looping Over values
for item in y.values():
print(item)
Using if
statement to get values
if "one" in y:
print(y['one']) # Output: uno
if "two" not in y:
print("Two not found")
if "three" in y:
del y['three']
Python dictionaries are a flexible and efficient data type that allow you to organize and manipulate data effectively. They are a fundamental part of Python and understanding them is crucial to becoming proficient in the language. Whether you’re storing configuration settings, managing data in a web application, or even building complex data structures, Python dictionaries are an excellent tool to have in your programming toolkit.
Top comments (0)