When getting a key from a Dictionary you're not sure exists, you would usually use TryGetValue
instead of ContainsKey
+ the get indexer to avoid the overhead of checking the key twice. In other words, this:
string password;
if (accounts.TryGetValue(username, out password))
{
// use the password
}
would be preferred to this:
if (accounts.ContainsKey(username))
{
string password = accounts[username];
}
What if I wanted to check if a key already existed before setting it to a value? For example, I would want to check if a username existed before overwriting it with a new password:
if (!accounts.ContainsKey(username))
{
accounts.Add(username, password);
}
else
{
Console.WriteLine("Username is taken!");
}
vs
// this doesn't exist
if (!accounts.TrySetValue(username, password))
{
Console.WriteLine("Username is taken!");
}
Is there a more performant alternative to ContainsKey
and Add
that does this?
You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().
To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.
python check if key in dictionary using try/except If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError. This can also be a way to check if exist in dict or not i.e. Here it confirms that the key 'test' exist in the dictionary.
If you think inserting a new name will be the common case and attempting to insert a duplicate will be the rare case you may just want to use the overhead of catching a exception.
try
{
accounts.Add(username, password);
}
catch (ArgumentException)
{
Console.WriteLine("Username is taken!");
}
If you call Add
with a existing key a ArgumentException
will be thrown. Even if you have frequent duplicates this will still be likely more performant than your ContainsKey
check.
I know i am late to this, but you can use a trick and store the count before the indexer set and check the count after the indexer set. If the counts are the same then you have overridden the key otherwise you have added a new mapping:
public static bool AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue>
dictionary, TKey key, TValue value)
{
var countBefore = dictionary.Count;
dictionary[key] = value;
return countBefore != dictionary.Count;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With