Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two Dictionaries [duplicate]

Given some Dictionaries

Dictionary<string, string> GroupNames = new Dictionary<string, string>(); Dictionary<string, string> AddedGroupNames = new Dictionary<string, string>(); 

I am unable to merge them into one:

GroupNames = GroupNames.Concat(AddedGroupNames); 

because "the type can't be implicitly converted". I believe (and my code proves me true) their type is the same - what am I overlooking?

like image 654
Alexander Avatar asked Nov 22 '13 17:11

Alexander


People also ask

Can you concatenate two dictionaries?

We can combine two dictionaries in python using dictionary comprehension. Here, we also use the for loop to iterate through the dictionary items and merge them to get the final output. If both the dictionaries have common keys, then the final output using this method will contain the value of the second dictionary.

How do you concatenate multiple dictionaries in Python?

Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

Do dictionaries allow duplicates?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Do Python dictionaries allow duplicates?

Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.


1 Answers

I think you defined your GroupNames as Dictionary<string,string>, so you need to add ToDictionary like this:

GroupNames = GroupNames.Concat(AddedGroupNames)                        .ToDictionary(x=>x.Key,x=>x.Value); 

Note that 2 original dictionaries would have different keys, otherwise we need some rule to merge them correctly.

like image 122
King King Avatar answered Oct 28 '22 08:10

King King