Home > Back-end >  How to update dictionary in multiple functions
How to update dictionary in multiple functions

Time:11-12

I need to update dictionary in multiple functions. With each function new Key:Values are added to dictionary and finally main dictionary should be updated. Can anyone shed some light on. I have tried below

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

def one():
    thisdict['new1'] = 'newvalue1'
    return thisdict

def two():
    thisdict['new2'] = 'newvalue2'
    return thisdict

print(thisdict)

I am getting below output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

but I want output to print

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'new1': 'newvalue1', 'new2': 'newvalue2'  }

CodePudding user response:

It appears you are not calling your functions that are supposed to be altering your Dict. Without calling them nothing will be updated.

Try calling them like so:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

def one():
    thisdict['new1'] = 'newvalue1'
    print('one, changed')

def two():
    thisdict['new2'] = 'newvalue2'
    print('two, changed')

one()
two()

print(thisdict) # will give you what you want

You initially had the functions returning the thisdict value, but from what I could see this is unnecessary as you have a global thisdict variable that simply needs to be changed. This is why I added the print statements so you can see how things are being altered.

CodePudding user response:

ended up calling all the five functions. Used update() in each function to update the dictionary.

  • Related