Different ways of adding to Dictionary
The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net
This is the This indexer:
public TValue this[TKey key]
{
get
{
int index = this.FindEntry(key);
if (index >= 0)
{
return this.entries[index].value;
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
this.Insert(key, value, false);
}
}
And this is the Add method:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
I won't post the entire Insert method as it's rather long, however the method declaration is this:
private void Insert(TKey key, TValue value, bool add)
And further down in the function, this happens:
if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
if (add)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.
So for all purposes and intents the performance is the same.
Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.
Sorry for the lengthy post, I hope it's okay.
Append a dictionary to a dictionary
You can do
orig.update(extra)
or, if you don't want orig
to be modified, make a copy first:
dest = dict(orig) # or orig.copy()
dest.update(extra)
Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
Difference of Dictionary.Add vs Dictionary[key]=value
Add -> Adds an item to the dictionary if item already exists in the dictionary an exception will be thrown.
Indexer or Dictionary[Key]
=> Add Or Update. If the key doesn't exist in the dictionary, a new item will be added. If the key exists then the value will be updated with the new value.
dictionary.add
will add a new item to the dictionary, dictionary[key]=value
will set a value to an existing entry in the dictionary against a key. If the key is not present then it (indexer) will add the item in the dictionary.
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Test", "Value1");
dict["OtherKey"] = "Value2"; //Adds a new element in dictionary
Console.Write(dict["OtherKey"]);
dict["OtherKey"] = "New Value"; // Modify the value of existing element to new value
Console.Write(dict["OtherKey"]);
In the above example, in first place dict["OtherKey"] = "Value2";
will add a new value in the dictionary because it doesn't exist, and in second place it will modify the value to New Value.
Add a new item to a dictionary in Python
default_data['item3'] = 3
Easy as py.
Another possible solution:
default_data.update({'item3': 3})
which is nice if you want to insert multiple items at once.
Adding a dictionary to another
foreach(var newAnimal in NewAnimals)
Animals.Add(newAnimal.Key,newAnimal.Value)
Note: this throws an exception on a duplicate key.
Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange
extension method that works on any ICollection<T>
, and not just on Dictionary<TKey,TValue>
.
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
if(target==null)
throw new ArgumentNullException(nameof(target));
if(source==null)
throw new ArgumentNullException(nameof(source));
foreach(var element in source)
target.Add(element);
}
(throws on duplicate keys for dictionaries)
Adding item to Dictionary within loop
In your current code, what Dictionary.update()
does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.
If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list
as a list and then append case
to it (instead of update) .
Example -
case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)
Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1
or entry2
, etc and the value being the corresponding dictionary for that entry.
case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.
Different ways to add and print keys/values to a dictionary in C#?
1. What the difference between this:
dict[1] = "hello"
and this:dict.Add(1, "hello")
?
Yes, there is a difference between using Add
and []
indexer property.
You can call dict[1] = "hello";
as many times as you want, but you can call dict.Add(1, "hello");
only once. Otherwise it will throw ArgumentException
saying An item with the same key has already been added.
2. Is there any way to add multiple entries (if I can call a pair of key and value that way) on the same line.
You can only add multiple items in one line using collection initialization syntax, when Dictionary
is created:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};
But, it will be transformed to Add
method calls by compiler anyway :)
Read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)
3. Is if there is a "better" way to print a dictionary, instead of doing it that way:
There is a way to print dictionary using one line expression, but I don't think it's more readable and it will use foreach
loop internally anyway, so wan't be faster either:
Console.WriteLine(string.Join(Environment.NewLine, dict.Select(x => string.Format("{0}: {1}", x.Key, x.Value))));
How to add multiple values to Dictionary in C#?
You can use curly braces for that, though this only works for initialization:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"},
{"s", "d"},
{"r", "m"}
};
This is called "collection initialization" and works for any ICollection<T>
(see link for dictionaries or this link for any other collection type). In fact, it works for any object type that implements IEnumerable
and contains an Add
method:
class Foo : IEnumerable
{
public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
// ...
}
Foo foo = new Foo
{
{1, 2, 3},
{2, 3, 4}
};
Basically this is just syntactic sugar for calling the Add
-method repeatedly. After initialization there are a few ways to do this, one of them being calling the Add
-methods manually:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
var anotherDictionary = new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
};
// Merge anotherDictionary into myDictionary, which may throw
// (as usually) on duplicate keys
foreach (var keyValuePair in anotherDictionary)
{
myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
Or as extension method:
static class DictionaryExtensions
{
public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
foreach (var keyValuePair in source)
{
target.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
myDictionary.Add(new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
});
Related Topics
How to Define Properties in Partial Classes, Then Mark Them with Attributes in Another Partial Class
When Not to Use Yield (Return)
What's the Difference Between Utf8/Utf16 and Base64 in Terms of Encoding
How to Copy File - Access to the Path Is Denied
How to Get the Last Four Characters from a String in C#
How to Generate Unique Public and Private Key via Rsa
Convert Data Type from Inherited Classes in C#
System.Badimageformatexception: Reference Assemblies Should Not Be Loaded for Execution
Best Practice for Exception Handling in a Windows Forms Application
Entity Framework Queryable Async
Writing to Output Window of Visual Studio
Forms' Does Not Exist in the Namespace System.Windows
How to Render an ASP.NET MVC View in PDF Format
Digital Signature in C# Without Using Bouncycastle
How to Implement Permission Based Access Control with ASP.NET Core
How to Count the Number of Elements That Match a Condition with Linq
How to Use Custom Authorize Attribute for Roles as Well as a Specific User