Home > Software engineering >  accessing nested dictionaries when you know the nested key?
accessing nested dictionaries when you know the nested key?

Time:09-25

This one is probably pretty easy, but I can't figure it out! Suppose I have a dictionary with a nested dictionary, that I know the nested dictionary key that I can store in a variable, how would I access this value?

k = 'mynested'
nestedk = 'blah'


x = {}
x['mynested'] = {}
x['mynested']['blah'] = 1


print(x[k[nestedk]])

throws error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

CodePudding user response:

There is a slight mistake in your last line print(x[k[nestedk]]). This line actually means that you are treating the k variable as a list which is actually a string and the characters of the string can only be accessed by an integer index and not by a string index.

Change the last line to the below

print(x[k][nestedk])

CodePudding user response:

You can get it with x[k][nestedk]. You can access the values similar to assigning values inside dictionary. As you are assigning X[k] = {} and x[k][nestedk] = 1

The value is 1 and key for nested object is k so initially we get the inner dictionary by x[k] and then we get the value using nested key in your case nestedk.

Thus you have to correct your print statement like below print(x[k][nestedk])

  • Related