如果我有一个包含列表,词典,字符串和整数的字典,我该如何复制该字典,但只能复制特定的白名单?
通过此功能过滤old_dict
会给我new_dict
。列出的白色键可以是任何格式,但解决方案应该能够获取任意白名单键的对象来产生输出。
old_dict = [
{
'name': {'first': "John", 'last': "Doe"},
'groups': ["foo", "bar"],
'widgets': [
{'id': 0, 'name': "Acme"},
{'id': 1, 'name': "Anvil"},
],
},
{
'name': {'first': "David"},
'groups': ["bar", "bash", "ding"],
'widgets': [
{'id': 1, 'name': "Anvil"},
{'id': 8, 'name': "Bingo"},
],
},
]
new_dict = [
{
'name': {'last': "Doe"},
'widgets': [
{'name': "Acme"},
{'name': "Anvil"},
],
},
{
'name': { },
'widgets': [
{'name': "Anvil"},
{'name': "Bingo"},
],
},
]
答案 0 :(得分:1)
new_dict = []
for dic in old_dic:
new_dict.append({})
for key in white_list: #list of keys
if key in dic:
new_dict[key] = old_dic[key]
您可以将列表理解作为:
new_dic = [ dict( key, old_dic[key])
for key in whitelist
if key in old_dic)
for dic in old_dic ]
答案 1 :(得分:1)
创建一个处理每种类型的递归函数,并在看到dict时过滤掉:
def keep_only(keys, val):
if type(val) is list:
return [keep_only(keys, v) for v in val]
if type(val) is dict:
return dict((k, keep_only(keys, v)) for k,v in val.items() if k in keys)
return val
样本用法:
>>> old_dict = [
{
'name': {'first': "John", 'last': "Doe"},
'groups': ["foo", "bar"],
'widgets': [
{'id': 0, 'name': "Acme"},
{'id': 1, 'name': "Anvil"},
],
},
{
'name': {'first': "David"},
'groups': ["bar", "bash", "ding"],
'widgets': [
{'id': 1, 'name': "Anvil"},
{'id': 8, 'name': "Bingo"},
],
},
]
>>> keep_only(set(['name', 'widgets', 'last']), old_dict)
[{'widgets': [{'name': 'Acme'}, {'name': 'Anvil'}], 'name': {'last': 'Doe'}}, {'widgets': [{'name': 'Anvil'}, {'name': 'Bingo'}], 'name': {}}]