How to key into deeply nested dictionary and list structure

Viewed 131

In the given

d = {'d1':[1,2,{'d2':['this is tricky',{'tough':[1,2,['me']]}]}]}

The questions asks me to print 'me'.

I tried to understand the given keys and values in the dictionary to find any relationship based on the key was unable to do so.

Is there a certain function is should be aware of before diving further?

2 Answers

Break it down into steps. You started with:

d = {'d1':[1,2,{'d2':['this is tricky',{'tough':[1,2,['me']]}]}]}
me = 'me'
tough = [1, 2, [me]]
d2 = ['this is tricky', {'tough': tough}]
d1 = [1, 2, {'d2': d2}]
d = {'d1': d1}

To access me from me from tough

print(tough[2][0])

To access me from tough from d2

print(d2[1]['tough'])

To access me from d2 from d1

print(d1[2]['d2'])

To access me from d1 from dict

print(d['d1'])

Chaining them all together

d['d1'][2]['d2'][1]['tough'][2][0]

We started with:

d = {'d1':[1,2,{'d2':['this is tricky',{'tough':[1,2,['me']]}]}]}

Let's see how we can navigate through the data, one step at a time:

>>> d = {'d1':[1,2,{'d2':['this is tricky',{'tough':[1,2,['me']]}]}]}
>>> d['d1']
[1, 2, {'d2': ['this is tricky', {'tough': [1, 2, ['me']]}]}]
>>> d['d1'][2]
{'d2': ['this is tricky', {'tough': [1, 2, ['me']]}]}
>>> d['d1'][2]['d2']
['this is tricky', {'tough': [1, 2, ['me']]}]
>>> d['d1'][2]['d2'][1]
{'tough': [1, 2, ['me']]}
>>> d['d1'][2]['d2'][1]['tough']
[1, 2, ['me']]
>>> d['d1'][2]['d2'][1]['tough'][2]
['me']
>>> d['d1'][2]['d2'][1]['tough'][2][0]
'me'

At the end, we have the desired code for the original problem: d['d1'][2]['d2'][1]['tough'][2][0].

Related