Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict.get('key') versus dict['key'] [duplicate]

Tags:

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.

like image 526
foundling Avatar asked May 21 '15 02:05

foundling


People also ask

Does dictionary allow duplicate keys in Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can you have duplicate keys in a dictionary?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

What is difference between D key and D get key?

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.

What happens if you use the same key multiple times while creating a dictionary?

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.


2 Answers

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 
like image 178
14 revs, 12 users 16% Avatar answered Sep 28 '22 07:09

14 revs, 12 users 16%


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. 
like image 32
Eric Renouf Avatar answered Sep 28 '22 07:09

Eric Renouf