Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add keyValuePair directly to Dictionary

I wanted to add a KeyValuePair<T,U> to a Dictionary<T, U> and I couldn't. I have to pass the key and the value separately, which must mean the Add method has to create a new KeyValuePair object to insert, which can't be very efficient. I can't believe there isn't an Add(KeyValuePair<T, U>) overload on the Add method. Can anyone suggest a possible reason for this apparent oversight?

like image 688
Dave Avatar asked Oct 22 '12 13:10

Dave


People also ask

How do you add a key-value pair to a dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

How to append a Key and value to a dictionary Python?

We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.


2 Answers

You can use the IDictionary<TKey,TValue> interface which provides the Add(KeyValuePair<TKey,TValue>) method:

IDictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary.Add(new KeyValuePair<int,string>(0,"0")); dictionary.Add(new KeyValuePair<int,string>(1,"1")); 
like image 155
DmitryG Avatar answered Sep 18 '22 18:09

DmitryG


Backup a minute...before going down the road of the oversight, you should establish whether creating a new KeyValuePair is really so inefficient.

First off, the Dictionary class is not internally implemented as a set of key/value pairs, but as a bunch of arrays. That aside, let's assume it was just a set of KeyValuePairs and look at efficiency.

The first thing to notice is that KeyValuePair is a structure. The real implication of that is that it has to be copied from the stack to the heap in order to be passed as a method parameter. When the KeyValuePair is added to the dictionary, it would have to be copied a second time to ensure value type semantics.

In order to pass the Key and Value as parameters, each parameter may be either a value type or a reference type. If they are value types, the performance will be very similar to the KeyValuePair route. If they are reference types, this can actually be a faster implementation since only the address needs to be passed around and very little copying has to be done. In both the best case and worst case, this option is marginally better than the KeyValuePair option due to the increased overhead of the KeyValuePair struct itself.

like image 34
Tim Copenhaver Avatar answered Sep 18 '22 18:09

Tim Copenhaver