【问题标题】:adding to a list of dictionaries - python添加到字典列表 - python
【发布时间】:2014-03-07 21:32:36
【问题描述】:

我正在尝试将新字典添加到现有字典列表中,该列表采用新键和值列表。

我的字典列表称为“选项”,它是这样的:

[{'powerpoint_color': 'blue', 'client_name': 'Sport Parents (Regrouped)'}, 
{'crossbreak': 'profile_julesage', 'chart_layout': '8', 'chart_type': 'pie', 'sort_order': 'desending'}]  

我想在选项中添加一个新的字典,但我不确定如何?

我想用一个名为“fixed_properties”的键来调用我的新字典,它将接受一个名为“fixed_elements”的字符串列表。

我尝试过这样的事情:

fixed_elements = []

options['fixed_properties'] = fixed_elements

但我得到了这个错误:

'dict' object has no attribute 'append' 

这就是我希望 'options' dict 的样子:

[{'powerpoint_color': 'blue', 'client_name': 'Sport Parents (Regrouped)'}, 
{'crossbreak': 'profile_julesage', 'chart_layout': '8', 'chart_type': 'pie', 'sort_order': 'desending'}
{'fixed_properties': ['q1','q4','q6']}]  

有什么建议吗?

谢谢。

【问题讨论】:

  • 您显示的代码不会产生该错误;相反,它将给出关于列表options 的非整数索引的错误。您实际上尝试了什么? (请注意,{} 是一个空字典,如果您实际尝试的是在其上附加 'q1' 等,那显然是行不通的。)
  • 我不好,fixed_elements 是一个空列表,它存储具有固定属性的问题。已更新。

标签: python list dictionary append


【解决方案1】:

如果options 是您的选项列表:

options.append({'fixed_properties': fixed_elements})

【讨论】:

  • 这行得通,谢谢。我这样做了:options.append({'fixed_props': fixed_elements})
【解决方案2】:

首先,您的options 变量是一个列表,因此options['fixed_properties'] 不起作用,因为您只能通过索引号引用列表中的对象。

你最好像这样构造你的 options 变量:

options = {
    "whatever_properties": {
        'powerpoint_color': 'blue',
        'client_name': 'Sport Parents (Regrouped)'
    }
}

这让您可以使用 options["whatever_properties"]["powerpoint_color"] 语法获得任何您想要的属性。

使用这个,你的代码 options["fixed_options"] = fixed_elements 就可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多