3

I have a dictionary that has dictionaries inside. I'm trying to access all the values in the keys inside. So I have:

d = {'key': 1, 'next': {'key': 5, 'next': {'key': 6, 'next': None}}}

And I'm hoping to get all the values of "key", so if all went well, I'd get:

1 5 6 None

I thought a basic loop would do the job, something like this:

for i in d:
    print(d['key'])

but I keep getting:

1 
1

How to I go about getting all the values in the dictionary?

Thanks for the help!

martineau
  • 119,623
  • 25
  • 170
  • 301
Landon G
  • 819
  • 2
  • 12
  • 31
  • 2
    Are you aware that you unconditionally print the value for outermost `key` in each loop? Are you aware that your dictionary only has two keys? – Yunnosch Feb 13 '19 at 19:32
  • Possible duplicate of [Python safe method to get value of nested dictionary](https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary) ... There are many others that are similar maybe there is a better one. – wwii Feb 13 '19 at 19:33
  • Are you trying to emulate [a LISP-style list](https://stackoverflow.com/questions/8073882/lisp-cons-in-python) in Python? – dan04 Feb 13 '19 at 19:42
  • @wwii I would not suggest using a general solution to this specific problem. OP clearly has not the level to understand the code you linked. Thanks for sharing though. – Benoît P Feb 13 '19 at 19:48

4 Answers4

3

Here is the newbie-friendly way of doing it:

d = {'key': 1, 'next': {'key': 5, 'next': {'key': 6, 'next': None}}}
current = d

while current:            # while current isn't None
    print(current['key'])     # print the current element
    current = current['next'] # Walk forward in the structure

I personally prefer to do it recursively:

def recursive(element):
    print(element['key'])         # print the current element
    if element['next']:           # If there is a next
        recursive(element['next'])    # call the same function on it

recursive(d)

The advantage of the recursive is that there is no "state" (no variables). And the function is more predictable as it doesn't depend on the correct initialisation of variables.

Benoît P
  • 3,179
  • 13
  • 31
0

You can use recursion:

d = {'key': 1, 'next': {'key': 5, 'next': {'key': 6, 'next': None}}}
def all_vals(_d, _param = 'key'):
  for a, b in _d.items():
    if a == _param:
      yield b
    if isinstance(b, dict):
      yield from all_vals(b, _param)

print(list(all_vals(d)))

Output:

[1, 5, 6]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Using a recursive function is a way out:

def recursive(d, result):

    result.append(d['key'])
    if 'next' in d and not (d['next'] == None):
        recursive(d['next'], result)
    return result

d = {'key': 1, 'next': {'key': 5, 'next': {'key': 6, 'next': None}}}
print(recursive(d, []))
Pedro Martins de Souza
  • 1,406
  • 1
  • 13
  • 35
0

nested_lookup module provides many Python functions for working with deeply nested documents

In your case

from nested_lookup import nested_lookup

d = {'key': 1, 'next': {'key': 5, 'next': {'key': 6, 'next': None}}}

print(nested_lookup('key', d))

Output:

[1, 5, 6]
Maharramoff
  • 941
  • 8
  • 15