2016-01-21 86 views
2

我試圖找出如何利用詞典列表:的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

回答

4

如果你確定列表中的每個項目實際上有必要的嵌套字典

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

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]