It allows you to provide a default value if the key is missing:
dictionary.get("bogus", default_value)
returns default_value (whatever you choose it to be), whereas
dictionary["bogus"]
would raise a KeyError.
If omitted, default_value is None, such that
dictionary.get("bogus") # <-- No default specified -- defaults to None
returns None just like
dictionary.get("bogus", None)
would.
Answer from unutbu on Stack OverflowGet dict value by key, default if doesn't exist or val is None
Why are there two ways to retrieve values from a dictionary in Python? - Software Engineering Stack Exchange
python - Return a default value if a dictionary key is not available - Stack Overflow
does dict.get() always try to resolve the default value?
Videos
It allows you to provide a default value if the key is missing:
dictionary.get("bogus", default_value)
returns default_value (whatever you choose it to be), whereas
dictionary["bogus"]
would raise a KeyError.
If omitted, default_value is None, such that
dictionary.get("bogus") # <-- No default specified -- defaults to None
returns None just like
dictionary.get("bogus", None)
would.
What is the
dict.get()method?
As already mentioned the get method contains an additional parameter which indicates the missing value. From the documentation
get(key[, default])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.
An example can be
>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1
Are there speed improvements anywhere?
As mentioned here,
It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.
Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)
def getway(d):
for i in range(100):
s = d.get(i)
def lookup(d):
for i in range(100):
s = d[i]
Now timing these two functions using timeit
>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979
As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis
>>> def lookup(d,val):
... return d[val]
...
>>> def getway(d,val):
... return d.get(val)
...
>>> dis.dis(getway)
2 0 LOAD_FAST 0 (d)
3 LOAD_ATTR 0 (get)
6 LOAD_FAST 1 (val)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>> dis.dis(lookup)
2 0 LOAD_FAST 0 (d)
3 LOAD_FAST 1 (val)
6 BINARY_SUBSCR
7 RETURN_VALUE
Where will it be useful?
It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces
if key in dic:
val = dic[key]
else:
val = def_val
To a single line, val = dic.get(key,def_val)
Where will it be NOT useful?
Whenever you want to return a KeyError stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!
Is it possible to have
getlike feature indict['key']?
Yes! We need to implement the __missing__ in a dict subclass.
A sample program can be
class MyDict(dict):
def __missing__(self, key):
return None
A small demonstration can be
>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'
Good day,
is there a way to get dictionary value or default if key doesn't exist OR value is None?
e.g.
x = { 'a': 1, 'c': None }
x.get('b', 2) # I want b = 2, I have it
x.get('c', 3) # I want c = 3, but key 'c' exists, so I get c = NoneI can of course create own dict object and override "get" or implement additional method, but maybe there's a fancy standard way?
p.s. simple practical example "for what":
You need to parse YAML file, there's array key "items":
items: - 1 - 2 - 3
If key is empty, any YAML parser set it to "None", however it's much better to have an empty list instead.
You can use dict.get()
Copyvalue = d.get(key)
which will return None if key is not in d. You can also provide a different default value that will be returned instead of None (unless the dict actually contains None as the value for this key):
Copyvalue = d.get(key, "empty")
Wonder no more. It's built into the language.
>>> help(dict)
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
...
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
...
I had this dict
d = {"a": 1, "b": 2, "c": 3}and my program would access the dict either by a key I knew was present, or by a string number, eg "1". If the key wasn't present, I wanted the method to return the key as an int (I knew that if it wasn't present it would always be a number). Basically I wanted this functionality:
d.get("a") # -> 1
d.get("9") # -> 9So I thought I could write
k = "a" d.get(k, int(k)) # ValueError: invalid literal for int() with base 10: 'k'
so even though "a" is a key in the dictionary, d.get() tries to parse int("a"). Intuitively it feels like it doesn't have to, because here the default value isn't needed.
Is there a reason for this? Just asking out of curiosity. I know there are workarounds, try statements and so on, but they are more verbose, and want to know if I'm missing something basic here..