Python:使用* args作为字典键

时间:2016-01-21 23:54:18

标签: python dictionary

我正在试图弄清楚如何获取字典列表:

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

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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]