Liondancer
Liondancer

Reputation: 16469

adding value to dictionary using update()

I am trying to add a value into my dictionary.

my dictionary:

a = {'a':[a,b,c],'b':[e,f,g]}

When I use the command a.update({'c':[j,k,l]}) and I try to print, I get a value of None

I am trying to get

a = {'a':[a,b,c],'b':[e,f,g], 'c':[j,k,l]}

Upvotes: 1

Views: 116

Answers (4)

Maxime Lorant
Maxime Lorant

Reputation: 36151

The update() method is inplace and returns None. The dict is modified by itself:

>>> a = {'a':[1,2,3],'b':[4,5,6]}
>>> a
{'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> a.update({'c': [9]})
>>> a
{'a': [1, 2, 3], 'c': [9], 'b': [4, 5, 6]}

I guess you're rewriting it with something like: a = a.update({'c': [9]}) and because of the None result, you get None...

Upvotes: 1

Garth5689
Garth5689

Reputation: 622

a = {'a':['a','b','c'],'b':['e','f','g']}

a.update({'c':['j','k','l']})

print a

gives:

{'a': ['a', 'b', 'c'], 'c': ['j', 'k', 'l'], 'b': ['e', 'f', 'g']}

Upvotes: 2

user2555451
user2555451

Reputation:

Your code works:

>>> a = {'a':['a','b','c'],'b':['e','f','g']}
>>> a.update({'c':['j','k','l']})
>>> print a
{'a': ['a', 'b', 'c'], 'c': ['j', 'k', 'l'], 'b': ['e', 'f', 'g']}
>>>

The problem is that dict.update is an in-place method. Meaning, it always returns None.

As I showed in my example, what you need to do is put the call to dict.update on its own line and then print the dictionary after that line.

Upvotes: 2

shx2
shx2

Reputation: 64318

update updates the dict in place and returns None.

Print a instead of the value returned by udpate.

Docs:

D.update([E, ]**F) -> **None**.  Update D from dict/iterable E and F.
If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]

Upvotes: 4

Related Questions