-1

I have a dictionary like so:

{
    a: {
        b: {
            c: "Hello World!"
        }
    }
}

And I have a deque like so:

deque(["a", "b", "c"])

I would like to print Hello World! using the two data structures above - how can this be done?

Ogen
  • 6,499
  • 7
  • 58
  • 124

2 Answers2

4

I dont know why you want to this but this may help:

 for i in deque(['a','b','c']):
     d= d[i]
 > d
 Hello World!

It only works if the dict has those keys, you can improve code as much as you can.
one more think is that the dictionary should have keys with ' like 'a'.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
2

If x is your dictionary, and y is your deque:

while y:
    x = x[y.popleft()]

x is now:

'Hello World!'

There are easier ways to accomplish this, like as @miradulo mentioned:

functools.reduce(operator.getitem, y, x)

But this makes use of popleft() which is a deque operation.

user3483203
  • 50,081
  • 9
  • 65
  • 94