Python dict重构
鉴于以下数据结构:Python dict重构,python,dictionary,generator,Python,Dictionary,Generator,鉴于以下数据结构: out = { 'foo': { 'public':{}, 'private':{}, 'other':{} }, 'bar': { 'public':{}, 'private':{}, 'other':{} } } 我正试图切掉子结构的一部分,以创建一个新的dict。我的用途是使用标记为private之外的所有数据响应请求 做相反的事是微不足道的: response = {x,y['private'] for x,y in out.iteritems()} 它为
out = {
'foo': { 'public':{}, 'private':{}, 'other':{} },
'bar': { 'public':{}, 'private':{}, 'other':{} }
}
我正试图切掉子结构的一部分,以创建一个新的dict
。我的用途是使用标记为private
之外的所有数据响应请求
做相反的事是微不足道的:
response = {x,y['private'] for x,y in out.iteritems()}
它为每个foo
和bar
构造一个dict,其中只包含标记为private
的数据。但是,标准库(可能是itertools)中是否有一些功能可以产生以下结果:
out = {
'foo': { 'public':{}, 'other':{} },
'bar': { 'public':{}, 'other':{} }
}
{x:(y['public'], y['other']) for x,y in out.iteritems()}
我尝试了以下方法:
out = {
'foo': { 'public':{}, 'other':{} },
'bar': { 'public':{}, 'other':{} }
}
{x:(y['public'], y['other']) for x,y in out.iteritems()}
尽管我不希望使用元组,也不希望显式地命名每个子结构,因为这是不可重用或不可伸缩的
def remove(name, obj):
return {x:y for x,y in obj.iteritems() if x is not name}
{x:remove('private',y) for x,y in out.iteritems()}
这似乎有效,但有更好的方法吗?有什么想法吗?这就是你的意思吗
respose={x:{'public':y['public'],'other':y['other']}对于x,y in out.iteritems()}
您可以将其分解为几个部分;你想要一本新字典,它删除了一些部分。因此,创建一个函数,该函数可以返回一个字典,而不返回有问题的元素,并调用它,这是迭代器的一部分
您使用的是词典理解,因此类似于这样的方法可以工作:
def remove_items(d, *items):
"""
Return dictionary copy with some items removed.
"""
return { a: b for a, b in d.iteritems() if a not in items }
print { x: remove_items(y, 'private') for x, y in out.iteritems() }
试试这个:
response = {}
for x,y in out.iteritems():
response[x] = dict(y)
del response[x]['private']
如果您不介意销毁原始词典,那么只需在其上迭代“private”元素,否则您需要复制第二级dicts,然后
del
不需要的项。谢谢,但我试图在响应中仅公开某些数据,而不是销毁原始内容。谢谢你的回答。这基本上是我最后一次尝试,但是我喜欢我可以在这里指定多个键的事实。这很好,很干净。谢谢。我喜欢你的答案比我的更笼统,但我还是会写删除项目
复制原件,然后del
删除不需要的项目。这样,您只需迭代[可能较短的]不需要的列表,而不是字典键的完整列表。@Duncan我原本打算建议在副本上使用del,但选择了一行。对于像dicts这样的简单数据类型,我怀疑这会更快。如果要删除的值是复杂类型,复制它们只是为了再次丢弃它们可能会更昂贵。