的Python:使用* ARGS作为字典键

问题描述:

我试图找出如何利用词典列表:的Python:使用* ARGS作为字典键

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

,但我也不太清楚如何指定我想要的,我需要他们的这一参数的具体顺序。有任何想法吗?

+0

您的预期结果是什么?什么是company_list,new_list在你的函数里面改变了,公司是什么?现在你总是返回一个空的列表,或者我错过了什么? – Cleb

+0

应该是'new_list.append'('谢谢你试着返回嵌套的值c – nahata5

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

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

你也可以遍历嵌套的字典[使用'reduce'](http://stackoverflow.com/a/16300379/748858) - - 尽管如此,这些天使用已经有点失宠了...... – mgilson

的重复拆包/导航是在反复做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]