Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Dictionary Methods | Other Data Types
/
Introduction to Python
セクション 4.  10
single

single

bookDictionary Methods

メニューを表示するにはスワイプしてください

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
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
タスク

スワイプしてコーディングを開始

Practice managing a grocery store inventory using a dictionary.

  • Create a dictionary called grocery_inventory with these items:
    • Milk: (113, "Dairy")
    • Eggs: (116, "Dairy")
    • Bread: (117, "Bakery")
    • Apples: (141, "Produce")
  • Get the details for "Bread" and save them in a variable called bread_details.
  • Add a new item "Cookies" with details (143, "Bakery").
  • Remove the item "Eggs" from the dictionary.

Print the following after each step:

  • The details of Bread: Details of Bread: <$bread_details>
  • The inventory after adding Cookies: Inventory after adding Cookies: <$grocery_inventory>
  • The inventory after removing Eggs: Inventory after removing Eggs: <$grocery_inventory>

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  10
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt