2017-10-19 46 views
0

所以我有一個看起來像這樣的功能:如何使用動態生成的密鑰訪問嵌套在另一個字典中的字典?

def get_thing_dict(self): 

    results = {} 
    grand_total = 0.0 

    # String looks like "a1,b,c1,d1,a2,b2,c2,d2" etc. 
    new_string = self.get_string().split(',') 

    while new_string[:4]: 

     # Get group of 4 
     new_string_line = new_string[:4] 

     # Split data 
     location = new_string_line[0] 
     description = new_string_line[1] 
     price = new_string_line[2] 
     qty = new_string_line[3] 

     # Add parts to dictionary 
     results[location] = {'description': description, 
           'price': price, 
           'qty': qty} 

     # Calculate and update total 
     line_total = float(price) * int(qty) 
     grand_total += line_total 

     # Remove used data 
     new_string = new_string[4:] 

    # Add total to dictionary 
    results['total'] = grand_total 

    return results 

字典看起來像:{'a1': {'description': 'b1', 'price': 'c1', 'qty': 'd1'}, 'a2': {'description': 'b2', 'price': 'c2', 'qty': 'd2'}, 'total': 1.0,}.

我需要那麼能夠通過在燒瓶字典迭代產生一個表看起來是這樣的:

<table> 
    <tr> 
     <td>b1</td><td>c1</td><td>d1</td> 
     <td>.....................................</td> 
     <td>.....................................</td> 
    </tr> 
    <tr> 
     <td>1.0</td> 
    </tr> 
</table> 

我無法弄清楚如何首先只能通過其值的鍵循環是另一個詞典不知道他們的密鑰,其次如何實際交流在不知道密鑰的情況下將嵌套字典中的項目放下。

有可能是一個非常顯而易見的答案,但我不認爲正確的問題如何詞來看看它在其他地方

回答

0

事情是這樣的:

for key1, val1 in d.items(): 
    if isinstance(val1, dict): 
     for key2, val2 in val1.items(): 
      # do what you need with inner dict key/vals here 
    else: 
     # do what you need with total key/val here 
0

看來你需要一個表來存儲和訪問數據

while new_string[:4]: 
     # Get group of 4 
     new_string_line = new_string[:4] 

     # Split data 
     location = new_string_line[0] 
     description = new_string_line[1] 
     price = new_string_line[2] 
     qty = new_string_line[3] 

     results.append([location, description, price, qty]) 

     # Remove used data 
     new_string = new_string[4:] 

    df = pd.DataFrame(results, columns=['location', 'description', 'price', 'qty']) 

    # if you want total number 
    total = (df.price * df.qty).sum() 


    location description price qty 
0  a1   b1 c1 d1 
1  a2   b2 c2 d2 

訪問數據

df[df.location == 'a1'] 
    location description price qty 
0  a1   b1 c1 d1