Thursday, 15 July 2010

update method of python dictionary did not work -



update method of python dictionary did not work -

i have 2 dictionaries.

a = {"ab":3, "bd":4} b = {"cd":3, "ed":5}`

i want combine them {'bd': 4, 'ab': 3, 'ed': 5, 'cd': 3}.

as this says, a.update(b) can finish it. when try, get:

type(a.update(b)) #--> type 'nonetype'

would explain me why cannot gain dict type?

i tried this, , did well:

type(dict(a,**b)) #-->type 'dict'

what difference between these 2 methods , why did first 1 not work?

as new python user has been frequent "gotcha" me seem forget it.

as have surmized, a.update(b) returns none, a.append(b) homecoming none list. these kinds of methods update info construction in place.

assuming don't want a modified, seek this:

from re-create import deepcopy c = deepcopy(a) c.update(b) type(c) #returns dict print(a) print(b) print(c)

that should it. other way of doing it:

c = dict(a,**b) type(c) #returns dict

is much improve imo. happening here b beingness unpacked, actually doing this:

c = dict(a, cd=3, ed=5) type(c) #returns dict

when done way, note if of keys in a duplicated in b, values replaced, e.g.:

a = {"ab":3, "bd":4} c = dict(a, ab=5) c #returns {"ab":5, "bd":4}

python dictionary

No comments:

Post a Comment