Calling a Key in a dictionary using a variable?

Question:

I am trying to be able to return the budget number for a specific dictionary based on a user defined variable. I am not having any luck figuring this out on my own, any help is greatly appreciated.

owners = ['rob','andre']
team_balance = {}

for name in owners:
    team_balance[name.capitalize()] ={'budget':200}

x='Rob' # x will be user defined using input()

print(team_balance[{x}]['budget'])

Trying the above results in the follwing error:

TypeError: unhashable type: 'set'
Asked By: TrevB

||

Answers:

You just need to leave out the curly braces like so:

print(team_balance[x]['budget'])

If you add them, the result is a set, which you can check like that:

isinstance({x}, set)

A set can’t be used as a dictionary key, because it is unhashable (which pretty much means it can be changed).

Answered By: LukasNeugebauer

The issue comes from the ‘{}’ in the last line.

When you defined your dictionary, you used strings as keys. So you have to use strings when you call a value from the dictionary.

x='Rob' also assigns a string in x, so is it good as it is.
We can use the function type to check the class of an object :

>>> type(x)
<class 'str'>

What’s wrong with the last line is the {x} that transform you string into a set of string. A set is like a list but unordered, unchangeable and with only uniques values.

>>> type({x})
<class 'set'>

So as you’re not using the same type of object to get than the one you use to set the values, it can’t work.

The error message you get

TypeError: unhashable type: ‘set’

is because a set object is unhasable, so it can’t be used as a dictionary key (it is explained why here). But even if a set would have been a hashable object, you wouldn’t have the value you wanted as it is not equal to what you used to define the keys.

Just remove the {} :

owners = ['rob','andre']
team_balance = {}

for name in owners:
    team_balance[name.capitalize()] ={'budget':200}

x='Rob' # x will be user defined using input()

print(team_balance[x]['budget'])


>>> 200
Answered By: yjn
owners = ['rob','andre']
team_balance = {}

for name in owners:
    team_balance[name.capitalize()] ={'budget':200}

x=input() # user will enter this value

Use try except to handle exception

try:
  print(team_balance[x.capitalize()]['budget']) 
except:
  print("Entered value not in owners list ")
Answered By: God Is One