Splitting the dictionary into multiple copies in python

I have a python dictionary

d = {
    'facets':{'style':"collared",'pocket':"yes"},   
    'vars':[    {'facets':{'color':"blue", 'size':"XL"}}, 
                {'facets':{'color':"blue", 'size':"L"}}   ]
}

Since there are 2 dictionaries in 'vars' key, i want to have 3 different dictionaries as given below. Please make it dynamically 3 documents as the the 'vars' can have any number of facets

d1 = {
    'facets':{'style':"collared",'pocket':"yes"}
} 
d2 = {
    'facets':{'color':"blue", 'size':"XL"}
}
d3 = {
    'facets':{'color':"blue", 'size':"L"}
}

Answers


Don't create separate variables. If you have 3 additional facet dictionaries in the vars key, you have to figure out how to create d4 as well, etc. Later on you suddenly have to now guess at how many d* variables exist.

Create a list instead:

facets = [{'facets': d['facets']}] + [facet for facet in d['vars']]

With a list, you can now simply loop over all the facets entries to manipulate or display them.

Demo:

>>> d = {
...     'facets':{'style':"collared",'pocket':"yes"},
...     'vars':[    {'facets':{'color':"blue", 'size':"XL"}},
...                 {'facets':{'color':"blue", 'size':"L"}}   ]
... }
>>> [{'facets': d['facets']}] + [facet for facet in d['vars']]
[{'facets': {'pocket': 'yes', 'style': 'collared'}}, {'facets': {'color': 'blue', 'size': 'XL'}}, {'facets': {'color': 'blue', 'size': 'L'}}]
>>> from pprint import pprint
>>> pprint(_)
[{'facets': {'pocket': 'yes', 'style': 'collared'}},
 {'facets': {'color': 'blue', 'size': 'XL'}},
 {'facets': {'color': 'blue', 'size': 'L'}}]

So the basic would be somthing like:

d1 = {k: v for (k,v) in d.iteritems() if k!= 'vars'}
other_ds = [ d1.copy().update(var) for var in d['vars'] ]

But you can modify to get exactly what you want, like:

d2 = d1.copy().update(d['vars'][0])

or (since python 3.5)

d2 = {**d1, **d['vars'][0]}

Or whatever combination you feel it's easier to understand.


Need Your Help

Entering form modal message loop without actual form showing

c# .net vb.net winforms

I have an WinForms application with one main form MainForm. This application has some scheduled operation being called in some intervals. This operation takes a lot of time to execute so it is laun...