stekala
stekala

Reputation: 51

python append dictionary in nested dictionary

i've this dictionary:

appointment = { soccer = {
                           day : 20,
                           month : april
                          }
               }

how can i insert this dictio in the same structure?

appointment = { gym = {
                           day : 5,
                           month : may
                          }
               }

expected output:

appointment = { soccer = {
                           day : 20,
                           month : april
                          },
                 gym = {
                           day : 5,
                           month : may
                          }
               }

how can i connect this dictio by code?

Upvotes: 1

Views: 26881

Answers (3)

mohamad khajezade
mohamad khajezade

Reputation: 181

If you are using python 3.5 or greater you can merge your dictionaries using the following syntax:

appointment1 = { 'soccer' : {
                        'day' : 20,
                       'month' : 'april'
                       }

            }
appointment2 = { 'soccer' : {
                        'day' : 20,
                        'month' : 'april'
                       },
              'gym' : {
                        'day' : 5,
                        'month' : 'may'
                       }
            }
appointment = {**appointment1,**appointment2}

Upvotes: 5

Zhenhir
Zhenhir

Reputation: 1215

If the dicts already exist you might look at dict.update().

Short answer is do this:

>>> appointment = { 'soccer' : { 'day': 20, 'month': 'april' } }
>>> appointment2 = { 'gym' : { 'day': 5, 'month': 'may' } }
>>> appointment.update(appointment2)
>>> appointment
{'gym': {'day': 5, 'month': 'may'}, 'soccer': {'day': 20, 'month': 'april'}}

But if you're making these dicts it makes more sense to just add new entries in the usual way (See: Add new keys to a dictionary?):

>>> appointment = { 'soccer' : { 'day': 20, 'month': 'april' } }
>>> appointment['gym'] = {'day': 5, 'month': 'may'}
>>> appointment
{'gym': {'day': 5, 'month': 'may'}, 'soccer': {'day': 20, 'month': 'april'}}

Upvotes: 3

avimehenwal
avimehenwal

Reputation: 1592

I think you are looking for dict.update() method

D.update([E, ]**F) -> None.

Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v

In either case, this is followed by: for k in F: D[k] = F[k]

Your case,

appointment = { 'soccer' : { 'day' : 20, 'month' :'april' }}
appointment2 = {'gym': {'day': 20, 'month': 'april'}}

# update appointment with appointment2 values
appointment.update(appointment2)
{'soccer': {'day': 20, 'month': 'april'}, 'gym': {'day': 20, 'month': 'april'}}

And appointment2 variable remains unchanged, when appointment variable is updated in place.

Upvotes: 1

Related Questions