6

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
pandita
  • 4,739
  • 6
  • 29
  • 51
  • Some of the values of the keys are dictionaries themselves, so I'd like to print them too – pandita Jun 20 '14 at 13:19
  • How about using `join`? e.g. `print "\n".join(mydict.keys())`. That will help with a single dictionary, but not subkeys. – mdml Jun 20 '14 at 13:19
  • 4
    @pandita Could you please provide an example of such a dictionary? Please also describe what is "nice" for you. –  Jun 20 '14 at 13:21

4 Answers4

5
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)
jaime
  • 2,234
  • 1
  • 19
  • 22
2

If you want concise code, try the pprint module.

import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)

There are some other solutions for nested dictionaries here: pretty printing nested dictionaries in Python?

Christian Berendt
  • 3,416
  • 2
  • 13
  • 22
nofinator
  • 2,906
  • 21
  • 25
2

I would suggest print it in

import json
json.dumps(dict, indent=4)
Christian Berendt
  • 3,416
  • 2
  • 13
  • 22
MK Yung
  • 4,344
  • 6
  • 30
  • 35
  • This will only work if all the objects in your dictionary are JSON serializable, i.e. no numpy arrays nor lambda functions for instance. – Aratz Apr 09 '18 at 07:05
0

You in fact can concatenate your list with your introduction string.Try this :

print "The keys in my dictionary are: " + ','.join([k for k in mydict.keys()])

*This would work only for non nested dictionaries though

shahharsh2603
  • 73
  • 2
  • 9