Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Dictionaries and Dictionary Methods | Other Data Types
Introduction to Python (copy)
course content

Kursusindhold

Introduction to Python (copy)

Introduction to Python (copy)

1. Getting Started
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

book
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.

1234567891011
# 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"])
copy

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:

123456789
# 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")])
copy

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 returns None. 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:

12345678910111213141516171819202122
# 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)
copy
Opgave

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 the bread_details variable.

  • Add a new item, "Cookies", with product ID 143 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>.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 7
toggle bottom row

book
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.

1234567891011
# 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"])
copy

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:

123456789
# 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")])
copy

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 returns None. 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:

12345678910111213141516171819202122
# 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)
copy
Opgave

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 the bread_details variable.

  • Add a new item, "Cookies", with product ID 143 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>.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 7
Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Vi beklager, at noget gik galt. Hvad skete der?
some-alt