繁体   English   中英

在python中将字典拆分为多个副本

[英]Splitting the dictionary into multiple copies in python

我有一个 python 字典

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

由于 'vars' 键中有 2 个字典,我想要 3 个不同的字典,如下所示。 请动态创建 3 个文档,因为“vars”可以有任意数量的方面

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

不要创建单独的变量。 如果您在vars键中有 3 个额外的方面字典,您还必须弄清楚如何创建d4等。稍后您突然必须现在猜测存在多少d*变量。

改为创建一个列表:

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

使用列表,您现在可以简单地遍历所有facets条目以操作或显示它们。

演示:

>>> 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'}}]

所以基本的东西是这样的:

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

但是您可以修改以获得您想要的内容,例如:

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

或(自 python 3.5 起)

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

或者你觉得更容易理解的任何组合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM