Question

I've been fighting with this for quite a long time and need some help, i have some loops searching something and dynamically create dictionary object for them, for example i am scanning a store then all the buckets and then the fruits inside those buckets.

from collections import defaultdict


def tree(): return defaultdict(tree)

test = tree()

test[Store][bucket][fruits] = defaultdict(list)

test[Store][bucket][fruits].append(1)

print test

"""
desired output

{
    'Store':{
        'bucket1':{
            'fruits':['banana', 'mango', 'apple']
            }
        },
        'bucket2':{
            'fruits':['banana', 'mango', 'apple']
            }
        }
}
"""

this approach throws an error and doesn't work, i also tried many other approaches like creating different dictionaries and then merging them, or creating list and then search or find and blah blah.. but i would like to find out how can i merge defaultdict objects inside each other. can someone please help me with this.

Thanks.

Was it helpful?

Solution

Given your desired output, I don't think you need to use defaultdict(list) at all.

Rather, you can use an ordinary list:

from collections import defaultdict

def tree(): 
    return defaultdict(tree)

test = tree()

test['Store']['bucket']['fruits'] = []
test['Store']['bucket']['fruits'].append(1)
test['Store']['bucket-13']['fruits'] = ['mango', 'apple', 'banana']

print test

However, if you do want to use defaultdict(list), the reason why it's throwing an error is because it is one level too low in your heirarchy. You want to assign it at the "bucket" level, rather then the "fruits" level:

test = tree()

test['Store']['bucket'] = defaultdict(list)

test['Store']['bucket']['fruit'].append('mango')  
test['Store']['bucket']['meat'].append('chicken') 

# 'fruit' and 'meat' now default to an empty list
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top