Python Forum

Full Version: Slicing a complex dictionary and list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I’m trying to test my understanding of indexing and key calls.

I’ve got a variable which is a combination of two dictionaries and four lists. It’s confusing and not very practical but just for fun I want to print the very last list item.

Here is the variable:
d = {"levelone":[1,2,{'leveltwo':[5,6,[1,['get me please']]]}]}
Here is my attempt to slice the final list item:
print(d['levelone'][2]['leveltwo'][2][1][0])
My interpreter (Jupyter Notebook) shows this traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-c2e6e77adf0d> in <module>()
----> 1 print(d['levelone'][2]['leveltwo'][2][1][0])

TypeError: string indices must be integers
This traceback is pointing to the slice of my list: ['levelone']. But it’s not actually a list slice, right? Why is it saying that the string slice must be an integer when it’s actually a dictionary key call? I figure I’m not properly referring to the first dictionary. According to the Dictionary tutorial by tutorialspoint, the valid syntax for pulling my first a key value would be d['levelone'].

Why is my interpreter saying there is an issue when there isn't?

Can someone please clarify?
Just walk through it. I get no error.
d = {"levelone":[1,2,{'leveltwo':[5,6,[1,['get me please']]]}]}

print(d['levelone'])
print(d['levelone'][2])
print(d['levelone'][2]['leveltwo'])
print(d['levelone'][2]['leveltwo'][2])
print(d['levelone'][2]['leveltwo'][2][1])
print(d['levelone'][2]['leveltwo'][2][1][0])
It works for me. You're sure the error is at ['levelone']? You can be sure by doing the indexing one step at a time: start with d['levelone'], then d['levelone'][2], and so on. If it is at ['levelone'], then the interpreter things d is a string. Check d to make sure what it is (not print(d), but just d, or print(repr(d))).