簡體   English   中英

如何使用動態生成的鍵訪問嵌套在另一個詞典中的詞典?

[英]How to access a dictionary nested in another dictionary with dynamically generated keys?

所以我有一個看起來像這樣的函數:

    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,}.

然后,我需要能夠遍歷flask中的字典,以生成如下所示的表:

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

我無法弄清楚如何首先不知道它們是鍵而僅循環訪問另一個字典的鍵,其次又如何在不知道鍵的情況下實際訪問嵌套字典中的項。

可能有一個非常明顯的答案,但我想不出如何正確表達該問題以便在其他地方查找它的方法

像這樣:

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

似乎您需要一個表來存儲和訪問數據

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM