简体   繁体   中英

Python - Update Value in one dictionary based on input from another

I am trying to figure out a way to manipulate one dictionary based on the input of a second dictionary. I am working on an exercise that simulates a vending machine. Based on the code below, my intent is to update the coin_stock dictionary based on the one of the options picked from the coin dictionary. For example if 'n' is chosen in menu_str, this means I have deposited a nickle. This would mean my coin_stock['nickles'] should be updated from 25 to 26. I am trying to generalize the code to update coin_stock when any of the coin options are entered in menu_str. I am pretty new to python. I have tried different things, but the code below is as close as I could get.

coin_stock = {'nickles':25, 'dimes':25, 'quarters':25, 'ones':0, 'fives':0}    
coin = { 'n': 5, 'd': 10, 'q': 25, 'o': 100, 'f': 500}

while True:

    menu_str = input("Indicate your deposit:")

    if menu_str in coin:
        if coin[menu_str] == 'n':

            coin_stock['nickles'] += 1

        if coin[menu_str] == 'd':
            coin[menu_str] = coin_stock['dimes']
            coin[menu_str] += 1

        if coin[menu_str] == 'q':
            coin[menu_str] = coin_stock['quarters']
            coin[menu_str] += 1

        if coin[menu_str] == 'o':
            coin[menu_str] = coin_stock['ones']
            coin[menu_str] += 1

        if coin[menu_str] == 'f':
            coin[menu_str] = coin_stock['fives']
            coin[menu_str] += 1

        coin_stock['nickles']+= 1
        print(coin_stock['nickles'])

Your if statements will not work, eg for a nickel, menu_str is n so coin[menu_str] is 5 . Just checking menu_str should do what you want

coin_stock = {'nickles':25, 'dimes':25, 'quarters':25, 'ones':0, 'fives':0}
coin = { 'n': 5, 'd': 10, 'q': 25, 'o': 100, 'f': 500}

while True:
    menu_str = input("Indicate your deposit: ")
    if menu_str == 'n':
        coin_stock['nickles'] += 1
    elif menu_str == 'd':
        coin_stock['dimes'] += 1
    elif menu_str == 'q':
        coin_stock['quarters'] += 1
    elif menu_str == 'o':
        coin_stock['ones'] += 1
    elif menu_str == 'f':
        coin_stock['fives'] += 1
    else:
        print("Exiting on invalid coin ({})".format(menu_str))
        break

print(coin_stock)

I'm going to use this as an opportunity to plug Python's powerful collection types.

Keeping Count

Check out the Counter() class in the collections library of Python's stdlib:

https://docs.python.org/2/library/collections.html#collections.Counter

Think of the Counter object as an overpowered dictionary, designed for keeping tally. It's nice for the use case of keeping tally of different coins types in a data store:

coin_store = Counter({'nickles': 25, 'dimes': 25, 'quarters': 25, 'ones': 0, 'fives': 0})
print(coin_store)  # Counter({'nickles': 25, 'dimes': 25, 'quarters': 25, 'ones': 0, 'fives': 0})
coin_store['nickles'] += 1
print(coin_store)  # Counter({'nickles': 26, 'dimes': 25, 'quarters': 25, 'ones': 0, 'fives': 0})

Merging Counters

For the question of finding "a way to manipulate one dictionary based on the input of a second dictionary" we can create a dictionary that contains all keys and values from one data store updated with the keys and values from another:

def update_store(coin_store1, coin_store2):
    """Updates the contents of a coin store with values from another store."""
    for coin_type, coin_num in coin_store2.items():
        coin_store1[coin_type] += coin_num

coin_store = Counter({'nickles': 6, 'dimes': 5, 'quarters': 10})
update_store(coin_store, Counter({'quarters': 5, 'ones': 3, 'fives': 10}))
print(coin_store)  # Counter({'quarters': 15, 'fives': 10, 'nickles': 6, 'dimes': 5, 'ones': 3})

Now you can use something like that in your code to update based on user input. Note: whatever update function you use requires error handling for invalid coin types and values.

Python Dictionaries

It's probably worth spending some time to understand the different operations supported by dictionaries, perhaps starting with .get() and .items() , and moving on to .update() and .copy() , etc. See them all here:

https://docs.python.org/2/library/stdtypes.html#mapping-types-dict

This should answer your question, and will hopefully get you interested in exploring the other types of collections offered in Python's stdlib as well. Best of luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM