Characteristics of Python Dictionary
Unordered: Unlike sequences (lists, tuples), dictionaries are unordered, which means the elements are not stored in any particular order.
Mutable: Dictionaries are mutable, which means you can add, delete, or modify elements after the dictionary has been created.
Key-Value Pair: The dictionary is a collection of key-value pairs, where each key is unique and associated with a value.
Indexed: Dictionaries are indexed using keys instead of numeric indices, unlike lists or tuples.
Dynamic: The size of the dictionary can change as elements are added or deleted from it.
Unchangeable Keys: The keys in a dictionary are immutable, which means they cannot be changed once they are created. Keys can only be of immutable data types like strings, numbers, or tuples.
Creating a Python Dictionary
To create a dictionary, we use curly braces ({}) with colon (:) separating the key-value pairs. Each key-value pair is separated by a comma (,).
Example:
# Creating a dictionary
student = {"name": "John", "age": 25, "city": "New York"}
In this example, we have created a dictionary student
with three key-value pairs, "name", "age", and "city".
Accessing Elements in a Python Dictionary
To access the elements in a dictionary, we use the key associated with it. The key serves as an index for the value.
Example:
# Accessing elements in a dictionary
print(student["name"]) # Output: John
print(student["age"]) # Output: 25
In this example, we have accessed the elements of the dictionary student
using the key.
Modifying Elements in a Python Dictionary
To modify an element in a dictionary, we access it using the key and then assign it a new value.
Example:
# Modifying elements in a dictionary
student["age"] = 26
print(student) # Output: {'name': 'John', 'age': 26, 'city': 'New York'}
In this example, we have modified the age of the student in the dictionary student
.
Adding Elements to a Python Dictionary
To add a new element to the dictionary, we use a new key-value pair.
Example:
# Adding elements to a dictionary
student["phone"] = "123-456-7890"
print(student) # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'phone': '123-456-7890'}
In this example, we have added a new key-value pair to the dictionary student
.
Deleting Elements from a Python Dictionary
To delete an element from a dictionary, we use the del
keyword with the key.
Example:
# Deleting elements from a dictionary
del student["phone"]
print(student) # Output: {'name': 'John', 'age': 26, 'city': 'New York'}
In this example, we have deleted the "phone" key-value pair from the dictionary student
.
No comments:
Post a Comment
Tell us how you like it.