【发布时间】:2021-03-24 17:49:12
【问题描述】:
我正在尝试追加到字典。有两个循环。键的名称取决于内部循环的值,而键是在循环内更新的变量的值。我的脚本是
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)
我得到错误名称“未定义附加值”。将不胜感激任何帮助。我想循环遍历 tot 和 (33,91) 范围的值。两者的每个组合都会给出一个唯一的值,我想创建一个字典,它将成为一个 csv,其中 x 值是行,a 是列。
谢谢!
已编辑:显示 append_value 函数
【问题讨论】:
-
您希望
append_value是什么?你有没有在某个地方定义它?此外,这似乎是一个语法错误:dict=['output'=x]那应该做什么? -
“附加到字典”是什么意思?为什么您期望
append_value被定义?请更清楚地说明您的问题。 -
不要给你的字典命名
dict——它会隐藏类型,并可能在你的程序的其他地方引起问题(以及令人困惑)。假设您将字典命名为my_data,那么my_data['output'] = x和my_data[head] = avg_PMI有什么问题 - 请阅读 Python 中字典使用的基础知识 docs.python.org/3/tutorial/datastructures.html#dictionaries -
感谢您的 cmets。我更新了代码以显示 append_value 函数定义。我纠正了一个错误,但我现在收到错误“append_value() 得到了一个意外的关键字参数‘head’”
标签: python loops dictionary for-loop