0

How can I evaluate a value at a specific key in a dict when using that key in a string variable (currency) to get the underlying values? What I'm trying now is:

offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = ['USD']

print(offer[currency])

and I want that to give

>>> [0.12, 0.15, 0.20, 0,50]

Is there any function or method that I'm missing?

martineau
  • 119,623
  • 25
  • 170
  • 301
steenou
  • 13
  • 1
  • Your string variable, `currency`, is actually a `list` object with one string element in it. To make it just a simple string, use `currency = 'USD'` as shown @Syntactic Fructose's answer. – martineau Mar 28 '18 at 19:59
  • https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey – Keyur Potdar Mar 28 '18 at 19:59

3 Answers3

2

You can just iterate on all the currencies, and do a .get on the dict:

In [75]: offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
    ...: currency = ['USD']
    ...: 

In [76]: for c in currency:
    ...:     print(offer.get(c, []))
    ...: 
[0.12, 0.15, 0.2, 0, 50]

Alternatively;

In [77]: for c in currency:
    ...:     print(offer[c]) # if all currency will exist within the dict
    ...:     
[0.12, 0.15, 0.2, 0, 50]
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • Perfect thanks! What's interesting is only your suggestion works: `for c in currency: print(offer.get(c, []))` But if you take it out of the for loop like `print(offer.get(currency, []))` I get a `TypeError: unhashable type: 'list'` error. Do you know why that is? – steenou Mar 29 '18 at 07:36
  • @steenou Well, in your original code, you are trying to access the values by a variable called as currency, which actually happens to be a list. Lists in Python are mutable, and are therefore unhashable (since their values could change on adding/removing elements). So when you try to use the variable currency directly to access the values, you are basically using an unhasable datatype as a key, which throws the error. I would suggest you read up more on python lists and dictionaries, and iterating within them. – Anshul Goyal Mar 29 '18 at 10:01
2

Just use a simple string to get your key, no need for brackets:

offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = 'USD'

print(offer[currency])
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

you can use this.

offer = {'USD': [0.12, 0.15, 0.20, 0,50]}
currency = offer['USD']
print(currency)
blacker
  • 768
  • 1
  • 10
  • 13
  • Yeah but the point is that I want to take `'USD'` from the variable `currency` cause `currency` have many other values and I don't want to make a big switch statement block – steenou Mar 29 '18 at 07:31