-4

I want to print the values of a nested dictionary in reverse order as a string for example given the dictionary

M = {
  'data': 'k',
  'list': {
     'data': 'c',
     'list' : {
        'data': 'i',
        'list' : {
           'data': 's',
           'list':False
        }
     }
  }
}    

should output

String = "sick"
khelwood
  • 55,782
  • 14
  • 81
  • 108

5 Answers5

4

Using a recursive approach,

def print_dict(d):
    if not d:
        return ''
    return print_dict(d['list']) + d['data']

Then you can call

M = {
    'data': 'k',
    'list': {
        'data': 'c',
        'list' : {
            'data': 'i',
            'list' : {
                'data': 's',
                'list': False
            }
        }
    }
}
print print_dict(M)

and it outputs

sick
nog642
  • 569
  • 3
  • 15
1

This does what you want:

M ={'data': 'k', 'list':{
'data': 'c', 'list' : {
'data': 'i', 'list' : {
'data': 's', 'list':False}}}}

from collections import abc
def nested_dict_iter(nested):
    for key, value in nested.items():
        if isinstance(value, abc.Mapping):
            yield from nested_dict_iter(value)
        else:
            yield value

print(''.join(reversed(list(nested_dict_iter(M))[:-1])))

Output:

sick

Some explanation:

From this answer, a dict is iterable and therefore you can apply the nested container iterable formula to this problem. This allows you to loop through the nested dictionary, while the yield returns a generator one item at a time.

Since the dictionary is nested, with one element at each depth, order is irrelevant. Finally, I converted the generator to a list, removed the last element (which is False) and then joined a reversed version of the list, which outputs the correct string.

user3483203
  • 50,081
  • 9
  • 65
  • 94
1

Here is a non-recursive approach:

def get_data(d):
    data = ''
    while d:
        data = d['data'] + data
        d = d['list']
    return data

print(get_data(M))

Output:

sick

The algorithm is simple: starts with d assigned to the nested dictionary. At each level, collect d['data'], then drill down to the next level util we hit False.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

You can use recursion:

M ={'data': 'k', 'list':{
'data': 'c', 'list' : {
'data': 'i', 'list' : {
'data': 's', 'list':False}}}}    
def flatten(s):
  return [b if a == 'data' else (lambda x:None if not isinstance(x, dict) else flatten(x))(b) for a, b in s.items()]
def flatten_data(a):
   if not isinstance(a, list):
      yield a
   else:
      for i in a:
        for b in flatten_data(i):
          yield b

final_data = ''.join(filter(None, list(flatten_data(flatten(M)))))

Output:

sick
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Is it what you are looking for ?

 import json
M = {
  'data': 'k',
  'list': {
     'data': 'c',
     'list' : {
        'data': 'i',
        'list' : {
           'data': 's',
           'list':False
        }
     }
  }
}
data=[]
def recursive_a(kl_1):

    for i,j in kl_1.items():
        if isinstance(j,dict):
            recursive_a(j)
    data.append(kl_1.get('data'))
    return 0


print(recursive_a(json.loads(json.dumps(M))))

print("".join(data))

output:

sick