Maryg
Maryg

Reputation: 105

Print nested dictionary in python3

How can I print a nested python dictionary in a specific format? So, my dictionary is looks like this:

dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}

I tried the following way:

for x, y in dictionary.items():
   print(x,":", y)

But it will printL`

Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}

How to get rid of the bracket and print the plain information?

I want to print on the following format:

Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;

:

Upvotes: 1

Views: 1083

Answers (2)

alexanderlz
alexanderlz

Reputation: 589

in your case 'y' is a dict, so if you want to print it differently you can override the repr (representation of the object) or dict. alternatively you can use some recursion here

def print_d(dd):
    if type(dd) != dict:
        return str(dd)
    else:
        res = []
        for x,y in dd.items():
            res.append(''.join((str(x),':',print_d(y))))
        return '; '.join(res)

if __name__=='__main__':
    dictionary = {'Doc1':{'word1': 3, 'word2': 1}, 'Doc2':{'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3':{'word1': 2}}

    for x, y in dictionary.items():
         print(x,": ", print_d(y))

Upvotes: 3

JacobIRR
JacobIRR

Reputation: 8946

Aside from the fact that your original dictionary declaration is not valid python unless each word is a defined variable, this seems to work:

import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))

Result:

Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2

Upvotes: 1

Related Questions