Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to print dictionary keys in a nice format [duplicate]

I'd like to get a nice output of all keys (and possibly subkeys) within a dictionary. Hence I wrote:

print("The keys in this dictionary are:\n")
for k in mydict.keys():
    print(k)

This works, however is there a more concise way to do this? I tried list comprehension, however this of course returns a list which I can't concatenate with may introduction string. Anything more functional that could be used?

EDIT: The dictionary might look like this:

mydict = {'key1':'value1',
          'key2':{'subkey1':'subvalue1','subkey2':'subvalue2'}}

I'm open to the meaning of 'nice formatting'. However, maybe something like this:

key1
key2: subkey1, subkey2
like image 714
pandita Avatar asked Jun 20 '14 13:06

pandita


2 Answers

def dump_keys(d, lvl=0):
    for k, v in d.iteritems():
        print '%s%s' % (lvl * ' ', k)
        if type(v) == dict:
            dump_keys(v, lvl+1)

mydict = {'key1':'value1',
          'key2':{'subkey1':'subvalue1',
                  'subkey2':'subvalue2',
                  'subkey3': {'subsubkey1' : 'subsubkeyval1'}}}

dump_keys(mydict)
like image 59
jaime Avatar answered Sep 28 '22 09:09

jaime


I would suggest print it in

import json
json.dumps(dict, indent=4)
like image 32
MK Yung Avatar answered Sep 28 '22 09:09

MK Yung