Ordbøker og Ordbokmetoder
# 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"])
# 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 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)
Oppgave
Swipe to start coding
Løsning
Alt var klart?
Takk for tilbakemeldingene dine!