Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing value in Dict
#1
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.
Reply
#2
Use dict.items() to get value and coin together.
for coin, value in coins.items():
   if value < n:
       print(coin)
       n -= value
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 62,253 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020