Return a default value if a dictionary key is not available
You can use dict.get()
value = 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
:
value = d.get(key, "empty")
Setting default value in Python dictionary if key is missing
You can use the set_default
method
my_dict = {"a":1,"b":2}
If a key exists, there is no change made to the existing value
my_dict.setdefault('a', 3)
print(my_dict) #{'a': 1, 'b': 2}
If it doesn't exist, the key-value pair is added
my_dict.setdefault('c', 3)
print(my_dict) #{'a': 1, 'b': 2, 'c': 3}
Looping through multiple keys :
my_dict = {"a":1,"b":2}
keys = ["a","c","d"]
for key in keys:
my_dict.setdefault(key, "Not Available")
print(my_dict) #{'a': 1, 'b': 2, 'c': 'Not Available', 'd': 'Not Available'}
Dictionary returning a default value if the key does not exist
TryGetValue
will already assign the default value for the type to the dictionary, so you can just use:
dictionary.TryGetValue(key, out value);
and just ignore the return value. However, that really will just return default(TValue)
, not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue)
{
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> defaultValueProvider)
{
return dictionary.TryGetValue(key, out var value) ? value : defaultValueProvider();
}
(You may want to put argument checking in, of course :)
Why dict.get(key) instead of dict[key]?
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.
Python Dictionary automatically check if value does not exist and return a default value
Yes you can leverage the get method of a dictionary. You can simply do
arr=[1,1,2,3,2,1]
freq={}
for i in arr:
freq[i] = freq.get(i,0)+1
Please Google for basic question like this before asking on stackoverflow
python dictionary .get() method with default value throws exception even when it should not even be executed
the issue with get
with a default value which needs build/evaluation is that the code is executed, even if not needed, which can slow down the code, or in your case trigger unnecessary errors.
An alternative could be:
port.get(server_name) or default()
If get
returns None
because a key is not found, then or default()
is activated. But if get
returns something, it short-circuits and default()
is not called.
(this could fail if get
returned empty string, zero, any "falsy" value but in your case - a server name - I'll suppose that it cannot happen)
Related Topics
Pandas: Adding New Column to Dataframe Which Is a Copy of the Index Column
Typeerror: Can't Convert 'Int' Object to Str Implicitly
Making Object JSON Serializable with Regular Encoder
Elegant Python Code for Integer Partitioning
Python Pandas Remove Duplicate Columns
What Are the Differences Between the Threading and Multiprocessing Modules
Python Regex Matching Unicode Properties
Skip the Headers When Editing a CSV File Using Python
Syntax Behind Sorted(Key=Lambda: ...)
Python3 --Version Shows "Nameerror: Name 'Python3' Is Not Defined"
Create Pandas Dataframe from Txt File with Specific Pattern
Pandas: Drop Consecutive Duplicates
How to Have Clusters of Stacked Bars
Very Large Matrices Using Python and Numpy
What Is the Purpose of "Pip Install --User ..."
How to Access the Ith Column of a Numpy Multidimensional Array
Importerror: Dll Load Failed: the Specified Module Could Not Be Found