Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get common keys and common values of two dictionaries

Hi I have two dictionaries of next type:

SortedDictionary<string, ClusterPatternCommonMetadata> PatternMetaData { get; set; }

The ClusterPatternCommonMetadata object looks like:

int ChunkQuantity { get; set; }

SortedDictionary<int, int> ChunkOccurrences { get; set; }

First I need the way to find keys of PatternMetaData that is exists in two dictionaries. I find this way:

List<string> commonKeysString=
            vector.PatternMetaData.Keys.Intersect(currentFindingVector.PatternMetaData.Keys)

Then I need to find common values of the founded keys...

Is there is the fast way (lambda, linq, etc) in order to do such operation

Thanks

like image 832
AlexBerd Avatar asked May 14 '12 15:05

AlexBerd


People also ask

How do you combine two dictionary values for common keys?

Using Counter The Counter function from the Collections module can be directly applied to merge the two dictionaries which preserves the keys. And in turn adds the values at the matching keys.

How do you compare keys in two dictionaries?

The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.


2 Answers

This is called intersection.

You can get the keys using

var data = dictionary1.Keys.Intersect(dictionary2.Keys)

If you want to find equal keys and values that are contained within both dictionaries then just

var equalDictionarys = dictionary1.Intersect(dictionary2);
like image 173
AlanFoster Avatar answered Sep 22 '22 14:09

AlanFoster


You can also get the whole Dictionary items which have common keys:

var commonDictionaryItems = Dic1.Where(d => Dic2.ContainsKey(d.Key)).ToList();
like image 36
mashta gidi Avatar answered Sep 18 '22 14:09

mashta gidi