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
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)
I would suggest print it in
import json
json.dumps(dict, indent=4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With