4

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • `print(dct["d1"][2]["d2"][1]["tough"][2][0])` – Andrej Kesely May 01 '21 at 21:34
  • When you say *"The questions asks me to print 'me'."*, if this is a homework or quiz, tell us what the question says. Because I assume they don't really expect you to code a recursive descent expansion of a nested dict until you find the desired string. Is the question merely asking what syntax you use to lookup the dict? surely not something more complex? – smci Jul 01 '22 at 23:22
  • The original version of this question used `dict` as a variable name. This is a bad idea, as it would shadow the built-in Python function `dict` (this means you cannot use `dict(...)` to create new dictionaries any more). See e.g. https://stackoverflow.com/questions/20406598. – Karl Knechtel Jul 01 '22 at 23:51

2 Answers2

6

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]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
flakes
  • 21,558
  • 8
  • 41
  • 88
1

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
se7en
  • 671
  • 4
  • 18
  • 1
    Please do NOT post images of code. Please copy and paste the text instead. Text is more accessible to everybody (be it screen readers, the google bot or people why simply want to copy part of the code) – Sören Jun 03 '22 at 06:13