簡體   English   中英

更新字典並使用循環值創建鍵值對

[英]Update dictionary and create key-value pairs with loop values

我正在嘗試將 append 寫入字典。 有兩個循環。 鍵的名稱取決於內部循環的值,而鍵是在循環內更新的變量的值。 我的腳本是

def append_value(dict_obj, key, value):
    # Check if key exist in dict or not
    if key in dict_obj:
        # Key exist in dict.
        # Check if type of value of key is list or not
        if not isinstance(dict_obj[key], list):
            # If type is not list then make it list
            dict_obj[key] = [dict_obj[key]]
        # Append the value in list
        dict_obj[key].append(value)
    else:
        # As key is not in dict,
        # so, add key-value pair
        dict_obj[key] = value

for x in range(tot):
  dict=['output'=x]

  for a in range(33,91):
        index_val=(a*sum_t)/x        

        # now i'm trying to create key names that would be year_33 year_34 and so on
        head=''
        head='year_{}'.format(a)

        append_value(dict, head=avg_PMI)

我得到錯誤名稱'append_value'未定義。 將不勝感激任何幫助。 我想循環遍歷 tot 和 (33,91) 范圍的值。 兩者的每個組合都會給出一個唯一的值,我想創建一個字典,它將成為 csv 其中 x 值是行,a 是列。

謝謝!

編輯:顯示 append_value function

錯誤的原因是當您使用head=avg_PMI調用 function 時, python 假定head是一個參數。 對於append_value ,唯一的 arguments 是dict_objkeyvalue 我假設您想向字典中添加一個值,例如 head=avg_PMI。 為此,您必須按以下方式調用 function append_valueappend_value(dict, head, avg_PMI)

暫無
暫無

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

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