Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a key exists in a Dictionary before adding it?

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?

like image 474
James Ko Avatar asked Aug 07 '15 04:08

James Ko


People also ask

How do you check for the existence of a key in a dictionary?

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().

How can you determine whether a key value pair exists in a dictionary?

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.

How do you check a key is exists in dictionary or not with out through KeyError?

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.


2 Answers

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.

like image 66
Scott Chamberlain Avatar answered Sep 21 '22 04:09

Scott Chamberlain


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;
}
like image 22
MaximGurschi Avatar answered Sep 22 '22 04:09

MaximGurschi