Why does this throw a KeyError:
d = dict() d['xyz']
But this does not?
d = dict() d.get('xyz')
I'm also curious if descriptors play a role here.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
The main difference between these two methods is what happens when the given key does not exist in the dictionary. When given such a key, d[key] will cause an error, and d. get(key) will just return None, signifying that there is no value associated with that key.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
This is simply how the get()
method is defined.
From the Python docs:
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
The default "not-found" return value is None
. You can return any other default value.
d = dict() d.get('xyz', 42) # returns 42
Accessing by brackets does not have a default but the get
method does and the default is None
. From the docs for get (via a = dict(); help(a.get)
)
Help on built-in function get: get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With