0

I have a nested dictionary in the form

'adipisci': {'foo': {'<UNK>': 2},
              'adipisci': {'<UNK>': 2},
              'non': {'adipisci': {'<UNK>': 2}}
              'est': {'<UNK>': 3},
              'tempora': {'<UNK>': 5}}

I need to generate

adipisci foo 2
adipisci adipisci 2
adipisci non adipisci 2
adipisci est 3
adipisci tempora 5

I have the following code but I am not getting expected results

def myprint(d,result):
    for k, v in d.items():
        if k=='<UNK>':
           print(result)
        if isinstance(v, dict):
            result+=' '+k
            myprint(v,result)
        else:
            print("{0} : {1}".format(k, v))
Rohit
  • 10,056
  • 7
  • 50
  • 82

1 Answers1

1

You should keep track of the parent keys as a path when making a recursive call, so that when you see the key UNK you can print the path along with the current value:

def myprint(d, path=None):
    if path is None:
        path = []
    for k, v in d.items():
        if k == '<UNK>':
            print(' '.join(path + [str(v)]))
        elif isinstance(v, dict):
            myprint(v, path + [k])

so that myprint(d) outputs:

adipisci foo 2
adipisci adipisci 2
adipisci non adipisci 2
adipisci est 3
adipisci tempora 5

Note that if you're using Python 3.5 or later versions, you can use generic unpacking to print the items of path:

print(*path, v)

instead of print(' '.join(path + [str(v)])).

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • @Phydeaux Please read https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument . – blhsing Mar 01 '19 at 21:35
  • error `can only concatenate str (not "list") to str` – Rohit Mar 01 '19 at 21:36
  • @Rohit I don't think you ran my example code correctly. Please run the demo here: https://repl.it/repls/MediumorchidWateryVerification – blhsing Mar 01 '19 at 21:37