0

给定以下数据结构:

out = {
  'foo': { 'public':{}, 'private':{}, 'other':{} },
  'bar': { 'public':{}, 'private':{}, 'other':{} }
}

我正在尝试出部分子结构以创建一个新的dict. 我的用途是用除了标记的所有数据来响应请求private

做相反的事情是微不足道的:

response = {x,y['private'] for x,y in out.iteritems()}

它为每个构造一个字典,foo并且bar只包含标记的数据private。但是标准库(也许是 itertools)中是否有一些功能会产生以下内容:

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()}

这似乎有效,但有更好的方法吗?有任何想法吗?

4

3 回答 3

2

您可以将其分解为多个部分;你想要一个删除了一些部分的新字典。因此,创建一个函数,该函数可以返回没有相关元素的字典,并将其称为迭代器的一部分。

您正在使用字典理解,所以这样的事情会起作用:

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() }
于 2012-08-16T11:55:06.333 回答
0

这就是你的意思吗?

respose = {x:{'public': y['public'], 'other': y['other']} for x,y in out.iteritems()}

于 2012-08-16T11:41:24.740 回答
0

尝试这个:

response = {}
for x,y in out.iteritems():
    response[x] = dict(y)
    del response[x]['private']

如果您不介意破坏原始字典,则只需对其del“私有”元素进行迭代,否则您需要复制第二级字典,然后复制del不需要的项目。

于 2012-08-16T11:58:02.777 回答