Python Forum

Full Version: Accessing value in Dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
Use dict.items() to get value and coin together.
for coin, value in coins.items():
   if value < n:
       print(coin)
       n -= value
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
Output:
Fifty = 50 Twenty = 20 Ten = 10 Five = 5 One = 1