Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple dictionaries into a single dictionary [duplicate]

Tags:

c#

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?

like image 856
dotnet-practitioner Avatar asked May 11 '12 22:05

dotnet-practitioner


People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

Can a dictionary have multiple dictionaries inside it?

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.

Can you have duplicates in a dictionary?

[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


2 Answers

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); 
like image 70
Magnus Avatar answered Sep 28 '22 15:09

Magnus


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

like image 31
Ry- Avatar answered Sep 28 '22 15:09

Ry-