Hannah
Hannah

Reputation: 137

How does dictionary setdefault method work?

I am doing the following in the python shell:

a = [0, 1]
b = [2, 4]
c = [2, 0]
d = [4, 3]

e = [a, b, c, d]
neighbour_list = {}

and i want to try the following:

neighbour_list.setdefault(x, [])

then

print(neighbour_list)

prints

{4: []}

I dont understand what it is doing. Why is x chosen by python to be 4?

Upvotes: 0

Views: 128

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336208

This will happen if x has been previously defined to be 4. Python didn't "choose to define" this, you must have.

In the code you provided, you're not showing how x was defined, but it definitely has been defined, or else you'd get a NameError:

>>> abcd_list = {}
>>> abcd_list.setdefault(x, [])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x=4
>>> abcd_list.setdefault(x, [])
[]
>>> abcd_list
{4: []}

Upvotes: 3

Related Questions