Home > Enterprise >  Calling a Key in a dictionary using a variable?
Calling a Key in a dictionary using a variable?

Time:05-25

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'

CodePudding user response:

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).

CodePudding user response:

The issue comes from the '{}' in the last line.

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

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 dictionnary key (it is explained why here). But even if a set would have been an hasable 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

CodePudding user response:

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 ")
  • Related