Python Diaries ….. Day 6
Dictionaries…
Today’s class is all about a versatile and powerful data structure: dictionaries. Dictionaries in Python allow us to store data in key-value pairs, providing a fast and efficient way to retrieve information based on unique keys. They are often likened to real-world dictionaries, where you look up a word (the key) to find its definition (the value).
In this class, we’ll explore how to create, manipulate, and leverage dictionaries in Python. Get ready to unlock a new level of data organization and retrieval! Let’s get started!
Creating a Dictionary
Dictionaries are created using curly braces {}
and consist of key-value pairs separated by colons :
# Example of a dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# output will be {'name': 'John Doe', 'age': 30, 'city': 'New York'}py
In this example, "name"
, "age"
, and "city"
are the keys, each associated with a respective value.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
# Example of a dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York",
"city": "Washington"
}
# output will be {'name': 'John Doe', 'age': 30, 'city': 'Washington'}
Accessing Values
You can access the value of a specific key using square brackets []
and the key itself.
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# Accessing values
name = person["name"] # Output: "John Doe"
age = person["age"] # Output: 30
You can also use get()
function to get the values.
name = person.get("name")
Modifying Dictionaries
Dictionaries are mutable, which means you can change the values associated with keys.
# Modifying values
person["age"] = 31
# using update function
person.update({"age":45})
Adding New Entries
You can add new key-value pairs to a dictionary.
# Adding a new entry
person["email"] = "john.doe@example.com"
Dictionary Methods
Dictionaries come with a variety of built-in methods for performing operations. Some commonly used methods include keys()
, values()
, and items()
.
# Getting keys, values, and items
keys = person.keys() # Output: dict_keys(['name', 'age', 'city', 'email'])
values = person.values() # Output: dict_values(['John Doe', 31, 'New York', 'john.doe@example.com'])
items = person.items() # Output: dict_items([('name', 'John Doe'), ('age', 31), ('city', 'New York'), ('email', 'john.doe@example.com')])
Removing Entries
You can remove a key-value pair from a dictionary using the pop()
,popitem()
,clear()
and del
method.
# Removing an entry using pop()
city = person.pop("city") # city is "New York", person no longer contains "city" key
# Removing an entry using popitem()
key, value = person.popitem() # Removes and returns the last key-value pair (key = 'city', value = 'New York')# Removing an entry using clear()
person.clear() # Removes all items from 'person' (person is now an empty dictionary)# Removing an entry using clear()
del person["age"], person["city"] # Removes both 'age' and 'city' keys and their associated values
Sorting a Dictionary
Dictionaries are inherently unordered, but you can sort them based on keys or values if needed. To sort a dictionary, you can use the sorted()
function with a key argument.
Sorting by Keys:
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
sorted_dict_by_keys = dict(sorted(person.items()))
print(sorted_dict_by_keys)
Sorting by Values:
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
sorted_dict_by_values = dict(sorted(person.items(), key=lambda item: item[1]))
print(sorted_dict_by_values)
Loop Through a Dictionary
Looping through a dictionary allows you to access its keys and values for various operations. There are several methods to achieve this:
Looping Through Keys: You can loop through the keys of a dictionary using a for
loop.
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for key in person:
print(key)
Looping Through Values: You can loop through the values of a dictionary using the values()
method.
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for value in person.values():
print(value)
Looping Through Both Keys and Values: You can loop through both the keys and values simultaneously using the items()
method.
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for key, value in person.items():
print(f"{key}: {value}")
Nested Dictionaries
A nested dictionary is a dictionary that contains other dictionaries as its values. This allows for more complex data structures.
students = {
"student1": {
"name": "John Doe",
"age": 20,
"major": "Computer Science"
},
"student2": {
"name": "Jane Doe",
"age": 21,
"major": "Mathematics"
}
}
You can access values in a nested dictionary by chaining the keys:
print(students["student1"]["name"]) # Output: John Doe
Dictionaries are a fundamental data structure in Python, providing an efficient way to organize and access data using unique keys. With their flexibility and versatility, dictionaries play a crucial role in a wide range of Python applications.
You can access the other topics in this tutorial series right here:
- Day 1: Data types, Comment, Type casting and User input.
- Day 2: Numbers, Strings, and Booleans.
- Day 3: Operators
- Day 4: Lists
- Day 5: Tuples and Sets
- Day 6: Dictionaries
- Day 7: If , If Else, If elif else Condition statements
- Day 8: While loops
- Day 9: For loops
- Day 10: Functions
- Day 11: File handling
- Day 12: Error Handling
- Day 13: Regular expressions
- Day 14: OOPS in python (class)
- Day 15: Python GUI libraries
In Day 7, we’ll explore condition statements in python. Keep up the great work! Happy coding!