Neeloy
Neeloy

Reputation: 11

How to use variables as key of dictionary in python

Hi I'm very new at python so asking for forgiveness if I'm asking very stupid question. So, I have this dictionary called array with some value, now I want to input the key as a variable and use that to print value assigned to that key.

array = {'color':'blue' , 'size':'small'}
print array ['color']

this works just fine, outputting the value blue. but if I try this it doesn't work.

array = {'color':'blue' , 'size':'small'}
var = input ('input a key') #input would be " color " or " size "
print array[var]

I think there is a very easy solution to this. thanks for helping in advance :)

Upvotes: 1

Views: 113

Answers (3)

Neeloy
Neeloy

Reputation: 11

Thanks guys, i finaly got it to working :)

mydict = {'color':'blue' , 'size':'small'}
var =str( raw_input ('input a key'))
print mydict[var]

seems all i needed was to get raw input and convert it to string

Upvotes: 0

Antonio Beamud
Antonio Beamud

Reputation: 2341

To avoid KeyError exception, you can use get:

>>> mydict = {'color':'blue' , 'size':'small'}
>>> var = input().strip()
' color '
>>> mydict.get(var, 'Not Found')

Upvotes: 2

timgeb
timgeb

Reputation: 78650

Your input has leading and trailing whitespace. For example, ' color ' is not the same as 'color'. Your dictionary has no key ' color '. You can strip the whitespace from an input string like this:

>>> mydict = {'color':'blue' , 'size':'small'}
>>> var = input().strip()
' color '
>>> mydict[var]
'blue'

By the way, your array is a Python dictionary, calling it array is a little confusing.

Upvotes: 2

Related Questions