2014-02-10 96 views
2

我想添加一個新的詞典到一個現有的詞典列表,它需要一個新的鍵和值的列表。添加到詞典列表 - python

我的字典的列表被稱爲「選項」,這是什麼樣子:

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

我想新的字典添加到選擇,但我不知道該如何?

我想用一個名爲「fixed_properties」的Key調用我的新字典,它將獲取一個名爲「fixed_elements」的字符串列表。

我想是這樣的:

fixed_elements = [] 

options['fixed_properties'] = fixed_elements 

但我得到這個錯誤:

'dict' object has no attribute 'append' 

這是我想的 '選項' 字典的樣子:

[{'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']}] 

有什麼建議嗎?

謝謝。

+0

您顯示的代碼不會產生該錯誤;它會給出一個有關列表'options'的非整數索引的錯誤。你實際上*嘗試了什麼? (請注意'{}'是一個空字典,如果你真正想要的是將'q1'等附加到它,那顯然是行不通的。) – geoffspear

+0

我的壞,fixed_elements是一個空列表,存儲的問題是有固定的財產。更新。 –

回答

1

如果options是你的選項列表:

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

這工作,謝謝。我這樣做:options.append({'fixed_props':fixed_elements}) –

1

首先,你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將工作。