【问题标题】:Splitting the dictionary into multiple copies in python在python中将字典拆分为多个副本
【发布时间】:2016-03-14 07:30:02
【问题描述】:

我有一本 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"}
}

【问题讨论】:

  • 发布你的尝试..
  • 不要按顺序命名变量。请改用列表。

标签: python python-2.7 python-3.x dictionary


【解决方案1】:

不要创建单独的变量。如果您在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'}}]

【讨论】:

    【解决方案2】:

    所以基本应该是这样的:

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

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

    【讨论】:

    • 编辑 (k,v) in dk,v in d.items()
    • 为什么要复制d1?生成的字典之间没有共享值。如果'vars' 中有两个以上的附加方面怎么办?
    • @MartijnPieters 我认为字典中不仅有'facets',而且需要合并。但是,如果不是这样,您是对的,我们可以跳过副本。
    • OP 未指定;给他们最简单的东西,提供他们预期的输出,而不用再猜测。您的解决方案太过分了,没有任何证据表明它是必要的。
    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2023-03-22
    • 1970-01-01
    • 2014-05-17
    • 2011-05-04
    • 2021-10-23
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多