Dictionaries and its Methods
✕Introduction to Dictionaries
- Unordered, Mutable collection of key-value pairs separated by comma
,enclosed in{} - Keys must be unique and immutable (string, number, tuple) but values can be any data type
- Used to store and lookup data using keys instead of index
my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"}print(my_dict)# {'name': 'Rabindra', 'age': 30, 'city': 'Kathmandu'}my_dict = {1: "one", (2, 3): "tuple key", "list": [1, 2, 3]}print(my_dict)# {1: 'one', (2, 3): 'tuple key', 'list': [1, 2, 3]}
Examples:
Dictionary Methods
- Functions that perform operations on dictionaries and return a new dictionary or modify the existing
- Data Related Operations:
get(),keys(),values(),items(),update(),pop() - Other: Membership,
len(),copy()
Accessing Data
[]is used to access value in a dictionary. Key is used instead of index to access value..get()method is also used to access value. It doesn't give error if key is not found- Apart from access
[]is also used to add/update key-value pairs in dictionary course_info = {"name": "Python Basics", "duration": 40, "instructor": "Rabindra"}print(course_info["name"])# Python Basicsprint(course_info.get("duration"))# 40print(course_info.get("level"))# None (key not found)print(course_info.get("level", 0))course_info["level"] = "Beginner"print(course_info)# New key is addedcourse_info["duration"] = 45print(course_info)# Existing value is updated
Examples:
Keys, Values and Items
.keys()returns a view of all keys in the dictionary.values()returns a view of all values in the dictionary.items()returns a view of all key-value pairs in the dictionarymy_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"}print(my_dict.keys())# dict_keys(['name', 'age', 'city'])print(my_dict.values())# dict_values(['Rabindra', 30, 'Kathmandu'])print(my_dict.items())# dict_items([('name', 'Rabindra'), ('age', 30), ('city', 'Kathmandu')])student_info = {"name": "Bob", "age": 25, "grade": "A"}print(student_info.keys())# dict_keys(['name', 'age', 'grade'])print(student_info.values())# dict_values(['Bob', 25, 'A'])print(student_info.items())# dict_items([('name', 'Bob'), ('age', 25), ('grade', 'A')])
Examples:
update
- Used to update a dictionary with key-value pairs from another dictionary
- If a key already exists, its value will be updated else new record will be added to the original dictionary.
my_dict = {"name": "Rabindra", "age": 30}update_dict = {"age": 35, "city": "Kathmandu"}my_dict.update(update_dict)print(my_dict)# {'name': 'Rabindra', 'age': 35, 'city': 'Kathmandu'}student_info = {"name": "Bob", "age": 25, "grade": "A"}update_info = {"grade": "A+", "city": "Los Angeles"}student_info.update(update_info)print(student_info)# {'name': 'Bob', 'age': 25, 'grade': 'A+', 'city': 'Los Angeles'}
Examples:
pop
- Used to remove a key from the dictionary and return its value
my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"}removed_value = my_dict.pop("age")print(removed_value)# 30print(my_dict)# {'name': 'Rabindra', 'city': 'Kathmandu'}student_info = {"name": "Bob", "age": 25, "grade": "A"}removed_grade = student_info.pop("grade")print(removed_grade)# Aprint(student_info)# {'name': 'Bob', 'age': 25}
Examples:
len
- Used to find the number of key-value pairs in a dictionary
my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"}print(len(my_dict))# 3student_info = {"name": "Bob", "age": 25, "grade": "A"}print(len(student_info))# 3
Examples:
copy
- Used to create a copy of a dictionary to avoid modifying the original dictionary
original_dict = {"name": "Rabindra", "age": 30}copied_dict = original_dictcopied_dict["age"] = 35print(original_dict)# {'name': 'Rabindra', 'age': 35}print(copied_dict)# {'name': 'Rabindra', 'age': 35}another_copy = original_dict.copy()another_copy["age"] = 40print(original_dict)# {'name': 'Rabindra', 'age': 35}print(another_copy)# {'name': 'Rabindra', 'age': 40}
Examples:
Membership
- Used to check if a key is present in the dictionary
my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"}print("name" in my_dict)# Trueprint("country" in my_dict)# Falsestudent_info = {"name": "Bob", "age": 25, "grade": "A"}print("grade" in student_info)# Trueprint("email" in student_info)# False- NOTE - Membership operator
inchecks for presence of key in the dictionary, not value. - For value, we use
inoperator with.values(). i.e.'Kathmandu' in my_dict.values()
Examples:
range
- Used to generate a sequence of numbers within a specified range
- Has three parameters:
start(inclusive),stop(exclusive) andstep(optional, default is 1) - Syntax:
range(start, stop, step) print(list(range(5)))# [0, 1, 2, 3, 4]print(list(range(1, 6)))# [1, 2, 3, 4, 5]print(list(range(0, 10, 2)))# [0, 2, 4, 6, 8]print(list(range(10, 0, -1)))# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Examples:
Collection Data Comparison
Comparison of Collection Data Types
| Property | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | No (Yes in recent versions) |
| Mutable | Yes | No | Yes | Yes |
| Unique | No | No | Yes | Yes (key) |
Comparison of collection data types
