What is Dictionary in Python?
First of All it is not sequential like Lists. It is a non-sequential, unordered, redundant and mutable collection as key:value pairs. Keys are always unique but values need not be unique. You use the key to access the corresponding value. Where a list index is always a number, a dictionary key can be a different data type, like a string, integer, float, or even tuples but never a List(it is Mutable!).
- 1.Python dictionaries are unordered collections of key-value pairs.
- 2.They are mutable, meaning you can add, remove, and modify elements after creation.
- 3.Dictionary keys must be unique and immutable (e.g., strings, numbers, tuples).
- 4.while values can be of any data type.
The contents of a dict can be written as a series of key:value pairs within braces { }, e.g.
dict = {key1:value1, key2:value2, ... }.
The “empty dict” is just an empty pair of curly braces {}.
{'a':'abc', 'k':'xyz'} == {'k':'xyz', 'a':'abc'} # Point 1- unordered collections of key-value pairs
output:- True
# Create a dictionary # Point 2 They are mutable, meaning you can add, remove, and modify elements after creation.
person = {"name": "John", "age": 30, "city": "New York"}
# Print the original dictionary
print("Original Dictionary:")
print(person)
# Add a new element
person["country"] = "USA"
# Print the updated dictionary
print("\nUpdated Dictionary after adding a new element:")
print(person)
# Modify an existing element
person["age"] = 31
# Print the updated dictionary
print("\nUpdated Dictionary after modifying an existing element:")
print(person)
# Remove an element
del person["city"]
# Print the updated dictionary
print("\nUpdated Dictionary after removing an element:")
print(person)
output:--
Original Dictionary:
{'name': 'John', 'age': 30, 'city': 'New York'}
Updated Dictionary after adding a new element:
{'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Updated Dictionary after modifying an existing element:
{'name': 'John', 'age': 31, 'city': 'New York', 'country': 'USA'}
Updated Dictionary after removing an element:
{'name': 'John', 'age': 31, 'country': 'USA'}
#Point 3.Dictionary keys must be unique and immutable (e.g., strings, numbers, tuples).
#Point 4.while values can be of any data type.
person = {
"name": "John",
"age": 30,
"city": "New York"
}
numbers = {
1: "one",
2: "two",
3: "three"
}
coordinates = {
(1, 2): "point1",
(3, 4): "point2",
(5, 6): "point3"
}
mixed_keys = {
"name": "John",
1: "one",
(2, 3): "point1"
}
##Note that while dictionaries can have keys of different data types, they must still be unique and immutable.