python setdefault in setdefault behavior
I tries to understand how nested setdefault works in code. I know how the basic setdefault works but I have a problem with figuring out such an code:
there are no keys in d, why both keys and values are added? "333" not in d so we're going to defult value d.setdefault("444",[]) -> we put a "444" key with a value [], setdefault return [] which we insert to "333" key which is returned by first setdefault and append is made(why for both new keys, I thought only for "333")
d = {'111': ['aaa', 'bbb'], '222': ['ccc']}
d.setdefault("333", d.setdefault("444",[])).append("ddd")
{'111': ['aaa', 'bbb'], '222': ['ccc'], '444': ['ddd'], '333': ['ddd']}
first is already in d, "ddd" is appended to the existing "111" key but why is there a new key "444"?
d = {'111': ['aaa', 'bbb'], '222': ['ccc']}
d.setdefault("111", d.setdefault("444",[])).append("ddd")
{'111': ['aaa', 'bbb', 'ddd'], '222': ['ccc'], '444': []}
first and the second key is already in d, only first updated?
d = {'111': ['aaa', 'bbb'], '222': ['ccc']}
d.setdefault("111", d.setdefault("222",[])).append("ddd")
{'111': ['aaa', 'bbb', 'ddd'], '222': ['ccc']}
second is in d,..?
d = {'111': ['aaa', 'bbb'], '222': ['ccc']}
d.setdefault("333", d.setdefault("222",[])).append("ddd")
{'111': ['aaa', 'bbb'], '222': ['ccc', 'ddd'], '333': ['ccc', 'ddd']}
thanks for the explanation
Solution 1:
It works like this:
>>> d = {'111': ['aaa', 'bbb'], '222': ['ccc']}
>>> first = d.setdefault("444",[])
>>> first
[]
>>> d
{'111': ['aaa', 'bbb'], '222': ['ccc'], '444': []}
>>> second = d.setdefault("333", first)
>>> second
[]
>>> d
{'111': ['aaa', 'bbb'], '222': ['ccc'], '444': [], '333': []}
>>> second.append("ddd")
>>> second
['ddd']
>>> d
{'111': ['aaa', 'bbb'], '222': ['ccc'], '444': ['ddd'], '333': ['ddd']}
Does that make it clear?
Note that first
and second
refer to the same list.
>>> first is second
True
>>> first.append('test')
>>> first
['ddd', 'test']
>>> second
['ddd', 'test']
>>> d
{'111': ['aaa', 'bbb'], '222': ['ccc'], '444': ['ddd', 'test'], '333': ['ddd', 'test']}