Return a Default Value If a Dictionary Key Is Not Available

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



Leave a reply



Submit