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")
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 :)
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
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'}
dict.get returns empty instead of default value
dict.get()
returns the default value only if the key is not set. But DictReader()
is setting the key, with an empty string as the value. That's because there is an empty string in that column.
In fact, DictReader()
guarantees that the there is a key set for every field name (where the field names are taken from the first row here); if a column is missing entirely, the value is set to None
.
You can trivially account for this by using or
:
firstname = row["firstname"] or "Company"
name = row["name"] or row["company"]
There is no point in using dict.get()
if a key is always there. But if row["firstname"]
is set to either an empty string or None
, then that's a value that is considered false, and so Python will produce the other operand to or
instead.
Python Dictionary return requested key if value does not exist
Should be possible with a lambda function
from collections import defaultdict
a = defaultdict((lambda : 'DNE'))
Edit: Sorry I misread the question. As the comment above already said. The way to go is extending the dict class.
>>> class mydict(dict):
... def __missing__(self,key):
... return key
...
>>> a = mydict()
>>> a['asd']
'asd'
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
Indeed, that won't be efficient at all.
As per comments, in .Net Core 2+ / NetStandard 2.1+ / Net 5, MS added the extension method GetValueOrDefault()
For earlier versions you can write the extension method yourself:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue ret;
// Ignore return value
dictionary.TryGetValue(key, out ret);
return ret;
}
Or with C# 7.1:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key) =>
dictionary.TryGetValue(key, out var ret) ? ret : default;
That uses:
- An expression-bodied method (C# 6)
- An out variable (C# 7.0)
- A default literal (C# 7.1)
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.
Related Topics
Convert Comma Separated String of Ints to Int Array
Deserialize JSON Array Stream One Item at a Time
Trying to Use the C# Spellcheck Class
How to Create a Hashcode in .Net (C#) for a String That Is Safe to Store in a Database
Why Are Properties Without a Setter Not Serialized
Silent Failures in C#, Seemingly Unhandled Exceptions That Does Not Crash the Program
How to Get Current User Timezone in C#
@Html.Dropdownlistfor How to Set Default Value
Why Cannot C# Generics Derive from One of the Generic Type Parameters Like They Can in C++ Templates
Is It Worthwhile to Initialize the Collection Size of a List<T> If It's Size Reasonably Known
Get All Controls of a Specific Type
How to Deserialize a JSON Property That Can Be Two Different Data Types Using JSON.Net
What Does Placing a @ in Front of a C# Variable Name Do
How to Get a Human-Readable File Size in Bytes Abbreviation Using .Net