Kurssisisältö
Introduction to Python (copy)
Introduction to Python (copy)
Dictionaries and Dictionary Methods
Dictionaries are perhaps the most versatile Python data structure. They store data as key-value pairs and are essential for situations where data needs to be retrieved quickly, and modifications are frequent.
In our grocery store scenario, dictionaries could efficiently handle supplier information, allowing each supplier to be accessed by its name or ID without the need to search through a list.
Watch as Alex demonstrates how to utilize dictionaries for our grocery store:
Creation
Dictionaries are created by enclosing comma-separated key-value pairs in curly braces {}
.
python
Ordering
Dictionaries preserve the insertion order of their elements, though it's essential to note that operations are typically conducted based on keys rather than position.
Mutability (Changeability)
Dictionaries are mutable, allowing you to add, update, or remove key-value pairs after the dictionary has been created;
Note
While dictionaries allow multiple values, each key must be unique within a dictionary. If a key is repeated during the assignment, the latest value will overwrite the previous, ensuring that each key has only one corresponding value.
Examples
Let's take a look at a simple dictionary. Instead of using index numbers, you access dictionary elements through their keys, which, in this case, are the names of the grocery items.
# Dictionary creation groceryItems = { "Milk": 3.49, "Eggs": 2.99, "Bread": 1.99, "Apples": 0.99 } # Extracting dictionary elements by their keys print("Price of Milk:", groceryItems["Milk"]) print("Price of Bread:", groceryItems["Bread"])
Dictionaries in Python are flexible when it comes to the types of data they can store.
The only restriction is that keys must be of an immutable (unchangeable) type (such as strings
, numbers
, or tuples
containing only immutable elements). This ensures that the key remains unchanged.
On the other hand, dictionary values can be of any type and may include mutable (changeable) types, such as lists or other dictionaries.
For instance:
# A dictionary with various types of keys and values store_info = { "Store Name": "Grocery Galore", # String key and string value 42: "Inventory Count", # Integer key and string value ("Bread", "Milk"): [2.99, 1.59] # Tuple key and list value (prices of bread and milk) } # Extracting dictionary element (list) by its key (tuple) print("Data under key ('Bread', 'Milk'):", store_info[("Bread", "Milk")])
Dictionary Methods
Dictionaries provide a range of operations and methods that facilitate efficient data handling. Here are some of the most commonly used methods:
get()
: retrieves the value for a specified key, and if the key is not found, it returnsNone
. This is different from using square brackets (e.g.,grocery_items["Milk"]
), which would raise an error if the key doesn't exist.;update()
: updates the dictionary with elements from another dictionary or an iterable of key-value pairs, overwriting existing keys;pop()
: removes a specified key and returns the corresponding value.
Note
In Python,
None
is a special value that means "nothing" or "no value", and it's often used when you want to show that something is empty or doesn't have a result.
Example Application
Imagine you need to update the dictionary for an inventory in your grocery store. Here's how you can do it using dictionary methods:
# Dictionary for a grocery store inventory inventory = { "Apples": 30, "Oranges": 18, "Bananas": 45 } # Get the count of Oranges print("Count of Oranges:", inventory.get("Oranges")) # Update inventory by adding a new item inventory.update({"Mangoes": 20}) print("Updated Inventory:", inventory) # You can also add a new item to the end of the dictionary like this inventory["Pineapples"] = 15 print("Updated Inventory:", inventory) # Remove Bananas from the inventory removed_item = inventory.pop("Bananas") print("Removed Item:", removed_item) print("Current Inventory:", inventory)
Swipe to start coding
Manage a grocery store's inventory using a dictionary, where each item is a key-value pair with the item’s name and details (product ID and category).
-
Define a dictionary
grocery_inventory
to store information:- "Milk": (113, "Dairy")
- "Eggs": (116, "Dairy")
- "Bread": (117, "Bakery")
- "Apples": (141, "Produce")
-
Retrieve the details of the item
"Bread"
from the dictionary and store them in thebread_details
variable. -
Add a new item,
"Cookies"
, with product ID143
and category"Bakery"
. -
Remove the item
"Eggs"
from the dictionary.
Output Requirements
- Print the details of
"Bread"
:Details of Bread: <$bread_details>
. - After adding
"Cookies"
, print the updated inventory:Inventory after adding Cookies: <$grocery_inventory>
. - After removing
"Eggs"
, print the updated inventory:Inventory after removing Eggs: <$grocery_inventory>
.
Ratkaisu
Kiitos palautteestasi!
Dictionaries and Dictionary Methods
Dictionaries are perhaps the most versatile Python data structure. They store data as key-value pairs and are essential for situations where data needs to be retrieved quickly, and modifications are frequent.
In our grocery store scenario, dictionaries could efficiently handle supplier information, allowing each supplier to be accessed by its name or ID without the need to search through a list.
Watch as Alex demonstrates how to utilize dictionaries for our grocery store:
Creation
Dictionaries are created by enclosing comma-separated key-value pairs in curly braces {}
.
python
Ordering
Dictionaries preserve the insertion order of their elements, though it's essential to note that operations are typically conducted based on keys rather than position.
Mutability (Changeability)
Dictionaries are mutable, allowing you to add, update, or remove key-value pairs after the dictionary has been created;
Note
While dictionaries allow multiple values, each key must be unique within a dictionary. If a key is repeated during the assignment, the latest value will overwrite the previous, ensuring that each key has only one corresponding value.
Examples
Let's take a look at a simple dictionary. Instead of using index numbers, you access dictionary elements through their keys, which, in this case, are the names of the grocery items.
# Dictionary creation groceryItems = { "Milk": 3.49, "Eggs": 2.99, "Bread": 1.99, "Apples": 0.99 } # Extracting dictionary elements by their keys print("Price of Milk:", groceryItems["Milk"]) print("Price of Bread:", groceryItems["Bread"])
Dictionaries in Python are flexible when it comes to the types of data they can store.
The only restriction is that keys must be of an immutable (unchangeable) type (such as strings
, numbers
, or tuples
containing only immutable elements). This ensures that the key remains unchanged.
On the other hand, dictionary values can be of any type and may include mutable (changeable) types, such as lists or other dictionaries.
For instance:
# A dictionary with various types of keys and values store_info = { "Store Name": "Grocery Galore", # String key and string value 42: "Inventory Count", # Integer key and string value ("Bread", "Milk"): [2.99, 1.59] # Tuple key and list value (prices of bread and milk) } # Extracting dictionary element (list) by its key (tuple) print("Data under key ('Bread', 'Milk'):", store_info[("Bread", "Milk")])
Dictionary Methods
Dictionaries provide a range of operations and methods that facilitate efficient data handling. Here are some of the most commonly used methods:
get()
: retrieves the value for a specified key, and if the key is not found, it returnsNone
. This is different from using square brackets (e.g.,grocery_items["Milk"]
), which would raise an error if the key doesn't exist.;update()
: updates the dictionary with elements from another dictionary or an iterable of key-value pairs, overwriting existing keys;pop()
: removes a specified key and returns the corresponding value.
Note
In Python,
None
is a special value that means "nothing" or "no value", and it's often used when you want to show that something is empty or doesn't have a result.
Example Application
Imagine you need to update the dictionary for an inventory in your grocery store. Here's how you can do it using dictionary methods:
# Dictionary for a grocery store inventory inventory = { "Apples": 30, "Oranges": 18, "Bananas": 45 } # Get the count of Oranges print("Count of Oranges:", inventory.get("Oranges")) # Update inventory by adding a new item inventory.update({"Mangoes": 20}) print("Updated Inventory:", inventory) # You can also add a new item to the end of the dictionary like this inventory["Pineapples"] = 15 print("Updated Inventory:", inventory) # Remove Bananas from the inventory removed_item = inventory.pop("Bananas") print("Removed Item:", removed_item) print("Current Inventory:", inventory)
Swipe to start coding
Manage a grocery store's inventory using a dictionary, where each item is a key-value pair with the item’s name and details (product ID and category).
-
Define a dictionary
grocery_inventory
to store information:- "Milk": (113, "Dairy")
- "Eggs": (116, "Dairy")
- "Bread": (117, "Bakery")
- "Apples": (141, "Produce")
-
Retrieve the details of the item
"Bread"
from the dictionary and store them in thebread_details
variable. -
Add a new item,
"Cookies"
, with product ID143
and category"Bakery"
. -
Remove the item
"Eggs"
from the dictionary.
Output Requirements
- Print the details of
"Bread"
:Details of Bread: <$bread_details>
. - After adding
"Cookies"
, print the updated inventory:Inventory after adding Cookies: <$grocery_inventory>
. - After removing
"Eggs"
, print the updated inventory:Inventory after removing Eggs: <$grocery_inventory>
.
Ratkaisu
Kiitos palautteestasi!