Chapter 7: Working with Lists and Dictionaries
Discover Python's core data structures, lists and dictionaries, which allow you to store and manage collections of data effectively.
In this chapter, we�ll explore lists and dictionaries in Python. These data structures are fundamental for organizing and managing data collections. By the end, you�ll be able to create, modify, and utilize lists and dictionaries in your programs.
Introduction to Lists
A list is an ordered collection of items that can store multiple values of different data types. Lists are defined using square brackets []
:
fruits = ["apple", "banana", "cherry"]
print(fruits)
In this example, fruits
is a list containing three items.
Accessing and Modifying Lists
You can access list items by their index and modify them directly:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits[1] = "blueberry"
print(fruits)
Here, we changed the second item in the list to "blueberry".
List Methods
Python provides various methods to work with lists. Here are some common ones:
append()
: Adds an item to the end of the list.insert()
: Inserts an item at a specific position.remove()
: Removes the first occurrence of an item.pop()
: Removes an item by index.sort()
: Sorts the list in ascending order.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Introduction to Dictionaries
A dictionary is a collection of key-value pairs, where each key is unique. Dictionaries are defined using curly braces {}
:
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person)
In this example, person
is a dictionary with three key-value pairs.
Accessing and Modifying Dictionaries
You can access and modify values in a dictionary using keys:
print(person["name"]) # Output: Alice
person["age"] = 30
print(person)
Here, we changed the value of the age
key to 30.
Dictionary Methods
Python provides various methods to work with dictionaries. Here are some useful ones:
keys()
: Returns a list of all keys in the dictionary.values()
: Returns a list of all values in the dictionary.items()
: Returns a list of key-value pairs.get()
: Retrieves a value for a specified key.pop()
: Removes an item by key.
print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(person.values()) # Output: dict_values(['Alice', 30, 'New York'])
Summary and Next Steps
In this chapter, we covered Python�s list and dictionary data structures, including how to create, modify, and use them. Lists and dictionaries are powerful tools for handling collections of data. In the next chapter, we�ll dive into working with files, where you�ll learn how to read from and write to files in Python.