Mathias Moesgaard
Mathias Moesgaard

Reputation: 11

Python - Append dictionary in dictionary

I am new to python and have a perhaps basic question.. I have a dictionary, and want to add another dictionary to a key in the first dictionary :)

So currently the dictionary look like this:

{
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}

And I need it to "append" another dictionary to an existing.. I guess It is a nested dictionary I need.

{
    "name": "custname",
    "slug": "custslug",
    "custom_fields": {
        "NavID": "10023"
    },
    "group": "1",
 }

Upvotes: 1

Views: 9476

Answers (4)

Rohit Khairnar
Rohit Khairnar

Reputation: 1331

dict = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}

another_dict = {
        "NavID": "10023"
    }

dict['Custom_fields'] = another_dict

Upvotes: 2

Prashant Kumar
Prashant Kumar

Reputation: 2092

If you want to append or merge 2 dictionaries, you can use update method.

Below is how you can do it :

d1 = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}
d2 = {"custom_fields": {"NavID": "10023"}}


d1.update(d2)

print(d1)

OUTPUT :

>>> {'group': '1', 'name': 'custname', 'custom_fields': {'NavID': '10023'}, 'slug': 'custslug'}

Upvotes: 0

Ayush Jain
Ayush Jain

Reputation: 376

In case you want a nested dictionary use the below method -

d1 = {"name": "custname","slug": "custslug","group": "1"}
d1["custom_fields"] = {"NavID": "10023"}
print(d1)

This will give the output you wanted.

Or if you want to merge two dictionaries and update the values, you may use the update method.

d1 = {"name": "custname","slug": "custslug","group": "1"}
d2 = {"NavID": "10023"}
d1.update(d2)

The output here will be

{"name": "custname","slug": "custslug","group": "1","NavID": "10023"}

Upvotes: 3

JimmyCarlos
JimmyCarlos

Reputation: 1952

Great question! This will work.

d1 = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}
d2 = {"NavID": "10023"}
d1["custom_fields"] = d2

Upvotes: 0

Related Questions