Home > Net >  How to assign an item/var as an updated dict
How to assign an item/var as an updated dict

Time:04-07

I have a code like this that assigns an item as dict that is an updated different dict:

lang1 = {1:'a',2:'b',3:'c'}
langs = {'lang1':lang1,'lang2':lang1.update({3:'g'})}
print(langs['lang2'])

When I do that I got the output 'None'. Is there anyway to do this so if I print(langs[lang2][3]) it gets 'g'

CodePudding user response:

dict.update does not return anything, it modifies the existing dict. if you are using python 3.9 and up you can do

lang1 | {3:'g'}

if you are not then you can do:

{**lang1, 3:'g'}

CodePudding user response:

Alternatively,

lang1 = {1:'a',2:'b',3:'c'}
lang2 = {1:'a',2:'b',3:'c'}
lang2.update({3:'g'})
langs = {'lang1':lang1, 'lang2':lang2}
print(langs['lang2'])

Recommend you to check out dict.update and various other methods:

https://www.w3schools.com/python/ref_dictionary_update.asp

  • Related