1

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;

:

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @alexanderlz. This works perfectly!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.