Home > Blockchain >  Updating a dictionary of dictionaries
Updating a dictionary of dictionaries

Time:11-08

Current issue: Taking input to select a dictionary key, and add in a quantity key:value pair to that nested dictionary.

This is my attempt

menu = {
    1: {"item": "Green Beret Omelette", "price": "$12.99"},
    2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
    3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
    4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
    5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
    6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}

selection = int(input("Please select your item:\n"))
if int(selection) < 1 or int(selection) > 6:
    print("Invalid selection. Please try again. \n")

count = int(input("Enter quantity: \n"))

# This is the line I'd like help with
menu[selection].update["quantity": count]

How do I structure the line menu[selection].update["quantity": count] so that menu would be updated to:

menu = {
    1: {"item": "Green Beret Omelette", "price": "$12.99", "quantity": 2},  # Note the new k:v here
    2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
    3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
    4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
    5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
    6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}

CodePudding user response:

Try this:

# Use 'dict.update()` with inputting a dict with key and value as you like
menu[selection].update({"quantity": count})

Run with input:

Please select your item:
1
Enter quantity: 
2

Output:

# print(menu)
{1: {'item': 'Green Beret Omelette', 'quantity': 2, 'price': '$12.99'},
 2: {'item': 'Get to the Chopped Salad', 'price': '$14.99'},
 3: {'item': 'Pump You Up Protein Shake', 'price': '$9.99'},
 4: {'item': "I'll Be Baby Back Ribs", 'price': '$22.99'},
 5: {'item': 'Let Off Some Steamed Vegetables', 'price': '$4.99'},
 6: {'item': 'The Ice Cream Cometh', 'price': '$15.99'}}
  • Related