【问题标题】:Update dictionary and create key-value pairs with loop values更新字典并使用循环值创建键值对
【发布时间】: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'] = xmy_data[head] = avg_PMI 有什么问题 - 请阅读 Python 中字典使用的基础知识 docs.python.org/3/tutorial/datastructures.html#dictionaries
  • 感谢您的 cmets。我更新了代码以显示 append_value 函数定义。我纠正了一个错误,但我现在收到错误“append_value() 得到了一个意外的关键字参数‘head’”

标签: python loops dictionary for-loop


【解决方案1】:

错误的原因是当你用head=avg_PMI调用一个函数时,python假定head是一个参数。对于append_value,唯一的参数是dict_objkeyvalue。我假设您想向字典中添加一个值,例如 head=avg_PMI。为此,您必须按以下方式调用函数append_valueappend_value(dict, head, avg_PMI).

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2017-12-20
    • 2018-11-03
    • 2020-05-18
    • 2021-12-04
    • 2021-05-13
    • 2013-11-01
    • 2023-02-03
    • 2017-04-24
    相关资源
    最近更新 更多