【问题标题】:Python: use *args as dictionary keyPython:使用 *args 作为字典键
【发布时间】:2016-01-21 23:54:18
【问题描述】:

我正在尝试找出如何获取字典列表:

some_list = [{'a':1, 'b':{'c':2}}, {'a':3, 'b':{'c':4}}, {'a':5, 'b':{'c':6}}] 

然后使用键的参数来获取这种情况下的嵌套值c。有什么想法吗?我试图做类似的事情:

def compare_something(comparison_list, *args):
    new_list = []
    for something in comparison_list:
        company_list.append(company[arg1?][arg2?])
    return new_list
compare_something(some_list, 'b', 'c')

但我不太确定如何指定我想要的参数的特定顺序,我需要它们。有什么想法吗?

【问题讨论】:

  • 您的预期结果是什么?什么是company_list,new_list在你的函数中在哪里改变,什么是company?现在你总是返回一个空列表还是我错过了什么?
  • 应该是 new_list.append( 感谢试图只返回嵌套 c 的值

标签: python dictionary


【解决方案1】:

如果您确定列表中的每个项目实际上都有必要的嵌套字典

for val in comparison_list:
    for a in args:
        val = val[a]
    # Do something with val

【讨论】:

  • 你也可以遍历嵌套的字典using reduce——不过,它的使用已经有点失宠了……
【解决方案2】:

Brendan's answer 中迭代完成的重复解包/导航也可以通过递归来完成:

some_list = [{'a':1, 'b':{'c':2}}, {'a':3, 'b':{'c':4}}, {'a':5, 'b':{'c':6}}]


def extract(nested_dictionary, *keys):
    """
    return the object found by navigating the nested_dictionary along the keys
    """
    if keys:
        # There are keys left to process.

        # Unpack one level by navigating to the first remaining key:
        unpacked_value = nested_dictionary[keys[0]]

        # The rest of the keys won't be handled in this recursion.
        unprocessed_keys = keys[1:]  # Might be empty, we don't care here.

        # Handle yet unprocessed keys in the next recursion:
        return extract(unpacked_value, *unprocessed_keys)
    else:
        # There are no keys left to process. Return the input object (of this recursion) as-is.
        return nested_dictionary  # Might or might not be a dict at this point, so disregard the name.


def compare_something(comparison_list, *keys):
    """
    for each nested dictionary in comparison_list, return the object
    found by navigating the nested_dictionary along the keys

    I'm not really sure what this has to do with comparisons.
    """
    return [extract(d, *keys) for d in comparison_list]


compare_something(some_list, 'b', 'c')    # returns [2, 4, 6]

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2021-12-17
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2023-03-27
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多