2

I'm trying to access a dictionary by using a variable that I've set previously.

myvar1 = 1
mydict =  {'1': ['apple', 20, 80, 40],
    '2': ['orange', 81, 400, 100]}

myvar2 = mydict[myvar1][0]
print(myvar2)

This gives me KeyError: 1

I've also tried

myvar2 = mydict['myvar1'][0]

This gives me KeyError: 'myvar1'

Clearly I am missing something basic.

0

3 Answers 3

4

myvar1 is an integer and mydict uses strings as keys. Either change myvar1 to be a string or change the dictionary to use integers as keys.

myvar1 = 1
mydict = {1: ['apple', 20, 80, 40],
          2: ['orange', 81, 400, 100]}
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

myvar1 = '1'

in your first statement. The 1 you're using is an integer, and not a character as in '1':

In [1]: 1=='1'
Out[1]: False

In [2]: str(1)=='1'
Out[2]: True

Comments

1
myvar1 = 1
mydict =  {1: ['apple', 20, 80, 40],
           2: ['orange', 81, 400, 100]}

myvar2 = mydict[myvar1][0]
print(myvar2)

First of all, your "keys" in mydict was strings and not integers while myvar = 1 is a integer so you need to keep the keys as integers as well for comparison. Unify your variable standards!

1 Comment

mydict[myvar1][0] is accessing the 0th element in the list, "apple". It isn't a dictionary key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.