Accessing value in Dict - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Accessing value in Dict (/thread-25747.html) |
Accessing value in Dict - Pioden - Apr-10-2020 I'm tearing my hair out trying to figure out what I'm doing wrong with access values in a dictionary! Here's a greedy algorithm for returning change - with the change value set to 75. def coin_change_greedy(n): coins = [50, 20, 10, 5, 1] i = 0 while(n>0): if(coins[i] > n): i = i+1 else: print(coins[i]) n = n-coins[i] print("\n") print('Coins in change') print(coin_change_greedy(75))Works nicely and prints out 50,20,5 as the answer. Now I wanted to change this to print out "Fifty, Twenty, Five", so I changed the list to a dictionary. This is my broken code def coin_change_greedy_2(n): coins = {'Fifty': 50,'Twenty': 20,'Ten': 10,'Five': 5,'One': 1} i = 0 while(n>0): if (coins[i] > n): i = i+1 else: print(coins.keys[i]) n = n-coins.values[i] print('Coins in change 2') print(coin_change_greedy_2(75))Unfortunately I can't figure out how to access the appropriate dict.key for the dict.value. In my head I thought coins.keys[0] would return 'Fifty', but I've got something wrong!! All help appreciated. RE: Accessing value in Dict - deanhystad - Apr-10-2020 Use dict.items() to get value and coin together. for coin, value in coins.items(): if value < n: print(coin) n -= value RE: Accessing value in Dict - TomToad - Apr-10-2020 you subscript the dictionary by key to get the value, so coins['Fifty'] will return 50. Unfortunately, the reverse does not work as values are not guaranteed to be unique. You can create a dynamic view with coins.items(), this will give you a list of tuples which then can be accessed as a pair for coin, value in coins.items(): print(coin,'=',value)Output
|