Given the following data structure:
out = {
'foo': { 'public':{}, 'private':{}, 'other':{} },
'bar': { 'public':{}, 'private':{}, 'other':{} }
}
I am attempting to slice out parts of the sub-structure to create a new dict. My use for this is to respond to requests with all data except that marked private.
To do the opposite is trivial:
response = {x,y['private'] for x,y in out.iteritems()}
Which constructs a dict for each foo and bar containing only the data marked private. But is there some functionality in the standard library (itertools perhaps) that would produce the following:
out = {
'foo': { 'public':{}, 'other':{} },
'bar': { 'public':{}, 'other':{} }
}
I have tried the following:
{x:(y['public'], y['other']) for x,y in out.iteritems()}
Although I would prefer to not use a tuple, and not explicitly name each sub-structure, as this is not reusable or scalable.
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()}
This seems to work, but is there a better way? Any ideas?
You can break this down into parts; you want a new dictionary which has some parts removed. So create a function which can return a dictionary without the elements in question and call this is part of an iterator.
You’re using dictionary comprehensions so something like this would work: