Lau*_*ber 3 python dictionary nested key list
我有一个迭代字典列表的函数,将指定的键值对返回到新的字典列表中:
data = [
{'user': {'login': 'foo1', 'id': 'bar2'}, 'body': 'Im not sure', 'other_field': 'value'},
{'user': {'login': 'foo2', 'id': 'bar3'}, 'body': 'Im still not sure', 'other_field': 'value'},
]
filtered_list = []
keys = ['user','body']
for i in data:
filt_dict = dict((k, i[k]) for k in keys if k in i)
filtered_list.append(filt_dict)
Run Code Online (Sandbox Code Playgroud)
该user密钥包含一个名为login;的子密钥。如何将其添加到keys参数列表中,而不是key user?
示例输出:
filtered_list = [
{'login': 'foo1', 'body': 'Im not sure'},
{'login': 'foo2', 'body': 'Im still not sure'},
]
Run Code Online (Sandbox Code Playgroud)
这个怎么样?假设您的密钥链实际上存在于您正在迭代的字典中。
设置
>>> from functools import reduce
>>> data = [{'user': {'login': 'foo1', 'id': 'bar2'}, 'body': 'Im not sure', 'other_field': 'value'},
... {'user': {'login': 'foo2', 'id': 'bar3'}, 'body': 'Im still not sure', 'other_field': 'value'}]
>>> keys = [('user', 'login'), ('body',)]
Run Code Online (Sandbox Code Playgroud)
解决方案
>>> [{ks[-1]: reduce(dict.get, ks, d) for ks in keys} for d in data]
[{'body': 'Im not sure', 'login': 'foo1'}, {'body': 'Im still not sure', 'login': 'foo2'}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313 次 |
| 最近记录: |