What is the best way to implement nested dictionaries?

后端 未结 21 1826
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  忘了有多久
    2020-11-22 00:48

    This is a function that returns a nested dictionary of arbitrary depth:

    from collections import defaultdict
    def make_dict():
        return defaultdict(make_dict)
    

    Use it like this:

    d=defaultdict(make_dict)
    d["food"]["meat"]="beef"
    d["food"]["veggie"]="corn"
    d["food"]["sweets"]="ice cream"
    d["animal"]["pet"]["dog"]="collie"
    d["animal"]["pet"]["cat"]="tabby"
    d["animal"]["farm animal"]="chicken"
    

    Iterate through everything with something like this:

    def iter_all(d,depth=1):
        for k,v in d.iteritems():
            print "-"*depth,k
            if type(v) is defaultdict:
                iter_all(v,depth+1)
            else:
                print "-"*(depth+1),v
    
    iter_all(d)
    

    This prints out:

    - food
    -- sweets
    --- ice cream
    -- meat
    --- beef
    -- veggie
    --- corn
    - animal
    -- pet
    --- dog
    ---- labrador
    --- cat
    ---- tabby
    -- farm animal
    --- chicken
    

    You might eventually want to make it so that new items can not be added to the dict. It's easy to recursively convert all these defaultdicts to normal dicts.

    def dictify(d):
        for k,v in d.iteritems():
            if isinstance(v,defaultdict):
                d[k] = dictify(v)
        return dict(d)
    

提交回复
热议问题