Boosted_d16
Boosted_d16

Reputation: 14062

adding to a list of dictionaries - python

I am trying to add a new dict to an existing list of dictionaries which takes a new key and list of values.

My list of dictionary is called "options" and this is what it looks like:

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

I'd like to add a new dict to the options but I am unsure how?

I'd like to call my new dict with a Key called "fixed_properties" and it will take a list of strings called "fixed_elements".

I tried something like this:

fixed_elements = []

options['fixed_properties'] = fixed_elements

But i got this error:

'dict' object has no attribute 'append' 

This is what I would like the 'options' dict to look like:

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

Any advice please?

Thanks.

Upvotes: 2

Views: 146

Answers (2)

ndpu
ndpu

Reputation: 22561

If options is your options list:

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

Upvotes: 1

cjfaure
cjfaure

Reputation: 201

Firstly, your options variable is a list, so options['fixed_properties'] wouldn't work because you can only reference objects in lists by their index number.

You'd be better off structuring your options variable like this:

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

This lets you get whatever properties you want using the options["whatever_properties"]["powerpoint_color"] syntax, for instance.

Using this, your code options["fixed_options"] = fixed_elements would work.

Upvotes: 1

Related Questions