Possible Duplicate:
Merging dictionaries in C#
dictionary 1
"a", "1"
"b", "2"
dictionary 2
"c", "3"
"d", "4"
dictionary 3
"e", "5"
"f", "6"
Combined dictionary
"a", "1"
"b", "2"
"c", "3"
"d", "4"
"e", "5"
"f", "6"
How do I combine the above 3 dictionaries into a single combined dictionary?
You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.
Since Python 3.9, it is possible to merge two dictionaries with the | operator. If they have the same key, it is overwritten by the value on the right. You can combine multiple dictionaries. Like += for + , |= for | is also provided.
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
var d1 = new Dictionary<string, int>(); var d2 = new Dictionary<string, int>(); var d3 = new Dictionary<string, int>(); var result = d1.Union(d2).Union(d3).ToDictionary (k => k.Key, v => v.Value);
EDIT
To ensure no duplicate keys use:
var result = d1.Concat(d2).Concat(d3).GroupBy(d => d.Key) .ToDictionary (d => d.Key, d => d.First().Value);
Just loop through them:
var result = new Dictionary<string, string>(); foreach (var dict in dictionariesToCombine) { foreach (var item in dict) { result.Add(item.Key, item.Value); } }
(Assumes dictionariesToCombine
is some IEnumerable
of your dictionaries to combine, say, an array.)
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