简体   繁体   中英

Understanding setdefault in Python

I am having a hard time understanding whats going on in the my code. So if I have the following line:

d = {}
d.setdefault("key",[]).append("item")

This returns

{'key': ['item']}

So I get what setdefault does. It checks for "key" in the d , a dictionary, and if it doesn't exist it creates it otherwise if it does exist then it returns the value. This returns a copy which can be manipulated and will be updated in the original dictionary. This is a new idea to me. Does this mean that setdefault returns a deep copy, as opposed to a shallow copy? Trying to get wrap my head around this shallow copy vs. deep copy.

it is equivelent to

item = d.get(key,default)
d[key] = item
d[key].action #in this case append

No Python operation does implicit copying. Ever. Implicit copying is evil, as far as Python is concerned.

It's literals that create objects. Every time setdefault is called, it evaluates both its arguments. When it evaluates its second argument ( [] ), a new list is created. It's completely the same as a = [] .

If you write el = [] and then try .setdefault ing el into some dict more than one time, you'll see that no copies are being made.

From the holy docs :

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

The behaviour is easily explicable once you drop the idea that it is a copy. It is not; it is the actual object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM