How to update value in dictionary?

S

ssecorp

dict.update({"a":1}) SETS the dict item "a" 's value to 1.

i want to increase it by 1. isnt that possible in an easy way? I
should use a tuple for this?
 
D

Diez B. Roggisch

ssecorp said:
dict.update({"a":1}) SETS the dict item "a" 's value to 1.

i want to increase it by 1. isnt that possible in an easy way? I
should use a tuple for this?


1) Don't use dict as name for a dictionary, it shadows the type dict

2) setdefault is your friend

d = {}
d['a'] = d.setdefault('a', 1) + 1

Diez
 
I

Iain King

dict.update({"a":1}) SETS the dict item "a" 's value to 1.

i want to increase it by 1. isnt that possible in an easy way? I
should use a tuple for this?

dict["a"] += 1

Iain
 
B

bearophileHUGS

ssecorp said:
dict.update({"a":1}) SETS the dict item "a" 's value to 1.

That works but it's not the right way to do that, use this:

d["a"] = 1

Bye,
bearophile
 
F

Fredrik Lundh

mblume said:
2) setdefault is your friend

d = {}
d['a'] = d.setdefault('a', 1) + 1
d['a'] = d.get('a', 1) + 1

seems to me a little better, as d['a'] doesn't get set twice, right?

setdefault is pronounced "get, and set if necessary". it only updates
the dictionary if the key isn't already there:
Help on built-in function setdefault:

setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

(since setdefault is a method, the second argument is evaluated whether
it's used or not, but that's true for your approach as well, and isn't
much of a problem for a light-weight object like the integer 1.)

</F>
 
M

MRAB

mblume said:
2) setdefault is your friend
d = {}
d['a'] = d.setdefault('a', 1) + 1
d['a'] = d.get('a', 1) + 1
seems to me a little better, as d['a'] doesn't get set twice, right?

setdefault is pronounced "get, and set if necessary".  it only updates
the dictionary if the key isn't already there:

 >>> help({}.setdefault)
Help on built-in function setdefault:

setdefault(...)
     D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

(since setdefault is a method, the second argument is evaluated whether
it's used or not, but that's true for your approach as well, and isn't
much of a problem for a light-weight object like the integer 1.)
Both

d['a'] = d.setdefault('a', 1) + 1

and

d['a'] = d.get('a', 1) + 1

will set d['a'] to 2 if 'a' isn't initially in d.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top