在参数列表中指定嵌套字典键

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)

tim*_*geb 5

这个怎么样?假设您的密钥链实际上存在于您正在迭代的字典中。

设置

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

  • @LaurieBamber 我假设您希望代码适用于*任何*键列表。如果你可以对按键进行硬编码,我的答案就太复杂了。如果您无法对密钥进行硬编码,则其他答案不会让您走得太远。;) (3认同)