TrevorPeyton
TrevorPeyton

Reputation: 669

Python Looping Entire Dictionary

I can't seem to find out how to do this after much searching.

Dict:

mdr = {'main': {'sm': {'testm': {'test1': 'test', 'test2': 'test'}}, 'lm': {}, 'l': {}}}

I would like it to look like this:

-Main
--SM
---Testm
----Test1:Test
----Test2:Test
--LM
--L

I won't know the exact amount of sub-directories it will process so I need to make a loop that will go through the entire direct. I only know how to display the whole directory if I know how far the dictionary goes. I would like it to display all possible keys if possible.

Upvotes: 1

Views: 134

Answers (3)

jpmc26
jpmc26

Reputation: 29964

I think recursion is a better bet than a loop. This is pretty close.

def print_dict(d, current_depth=1):
    for k, v in d.items():
        if isinstance(v, dict):
            print '-' * current_depth + str(k)
            print_dict(v, current_depth + 1)
        else:
            print '-' * current_depth + str(k) + ':' + str(v)

Output (after fixing the syntax of your dictionary):

>>> print_dict(mdr)
-main
--lm
--l
--sm
---testm
----test1:test
----test2:test

The case is off from your desired output, but you should be able to handle that. If you want to preserve the original order, then you need to use an OrderedDict instead of a dict. dict is a hash table, so it could do anything with the order. (Luckily, the isinstance(v, dict) test still works on OrderedDict.)

Upvotes: 4

bozdoz
bozdoz

Reputation: 12880

You should show what you have tried.

Regardless, I thought it was a fun project. What do you think of my solution? It doesn't include the unexpected caps that are in your preferred result. But, then, how can you expect the unexpected?

def dict_tree(d, i = 1):
    for key, value in d.items():
        if isinstance(value, dict):
            print '-' * i + key
            dict_tree(value, i + 1)
        else:
            print '-' * (i + 1) + key + ':' + value

Should output:

-main
--lm
--l
--sm
---testm
-----test1:test
-----test2:test

Upvotes: 1

bnlucas
bnlucas

Reputation: 1774

def tree(data, indent=0):
    if isinstance(data, basestring):
        print '{i}{d}'.format(i='-'*indent, d=data)
        return
    for key, val in data.iteritems():
        if isinstance(val,  dict):
            print '{i}{k}'.format(i='-'*indent, k=key)
            tree(val, indent + 1)
        else:
            print '{i}{k}:{v}'.format(i='-'*indent, k=key, v=val)

tree(mdr)

Output:

main
-sm
--lm
--testm
---test1:test
---test2:test
--l

Input from the console (in response to the comment on this answer):

>>> mdr = {'main': {'sm': {'testm': {'test1': 'test', 'test2': 'test'}, 'lm': {}, 'l': {}}}}
>>> def tree(data, indent=0):
        if isinstance(data, basestring):
            print '{i}{d}'.format(i='-'*indent, d=data)
            return
        for key, val in data.iteritems():
            if isinstance(val,  dict):
                print '{i}{k}'.format(i='-'*indent, k=key)
                tree(val, indent + 1)
            else:
                print '{i}{k}:{v}'.format(i='-'*indent, k=key, v=val)

>>> tree(mdr)
main
-sm
--lm
--testm
---test1:test
---test2:test
--l
>>> 

Upvotes: 1

Related Questions