【问题标题】:Specifying nested dictionary key in list of arguments在参数列表中指定嵌套字典键
【发布时间】:2019-03-02 15:16:36
【问题描述】:

我有一个函数可以遍历一个字典列表,将指定的键值对返回到一个新的字典列表中:

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)

user 键包含一个名为login 的子键;如何将其添加到键参数列表中,而不是键 user

样本输出:

filtered_list = [
    {'login': 'foo1', 'body': 'Im not sure'},
    {'login': 'foo2', 'body': 'Im still not sure'},
]

【问题讨论】:

  • 伪代码keys的输出究竟应该是什么样子?
  • 见上面的编辑。
  • 我们可以将keys 结构更改为元组列表吗?例如,[('user', 'login'), ('body',)]
  • 是的,这很好,除了登录字段,例如(“登录”,“正文”)。
  • 顺便说一句,您应该修复正文字符串中的引号。

标签: python list dictionary nested key


【解决方案1】:

如果您确定列表中的所有元素(字典)都将具有您指定的键,那么一个快速的解决方案可能是:

filtered_list = [
    {
        'login': elem['user']['login'],
        'body': elem['body'],
    }
    for elem in data]

这对丢失的键没有错误处理。

【讨论】:

    【解决方案2】:

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

    设置

    >>> 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',)]
    

    解决方案

    >>> [{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'}]
    

    【讨论】:

    • 我将 Ralf's 标记为正确答案,因为它很简单,但是您的代码也可以正常工作,因此感谢您的努力。
    • @LaurieBamber 我假设您希望代码适用于 any 键列表。如果您可以对密钥进行硬编码,那么我的答案就太复杂了。如果您无法对密钥进行硬编码,那么其他答案不会让您走得太远。 ;)
    • @LaurieBamber 此代码处理任意长度的keys 列表和任意深度的嵌套字典。拉尔夫的回答很好,但它被锁定在问题中显示的特定结构中,所以如果您需要处理不同的键,您必须编辑代码。
    • 这是一个很好的回应
    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2020-12-15
    • 2021-10-20
    • 2023-03-29
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多