Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two dictionaries (Key, value) and return Keys that doesn't have same value

I'm bit new to c# and want to identify keys that doesn't have same value while comparing two dictionaries.

The dictionary I have is of dict => KeyValuePair<string, string>. And I have two dictionaries like -

dict1 => {"a":"False","b":"amazonaws.com","c":"True"}
dict2 => {"a":"True","b":"amazonaws.com","c":"False"}

I want to compare both dictionaries and return a variable which will have Keys ["a", "c"] as for the above example, those keys have different value.

Currently the logic I have written will only differentiate keys that's not there in the other dictionary.

Dictionary dictExcept = null;
foreach (IDictionary kvp in dict1.Cast<object>().Where(kvp => !dict2.Contains(kvp)))
    {
        dictExcept.Add(kvp.Keys, kvp.Values);
    }
return dictExcept ;
like image 810
Biswajit Maharana Avatar asked Dec 15 '21 12:12

Biswajit Maharana


People also ask

How do I compare two dictionary keys and values in Python?

Python List cmp() Method. 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.

Can we compare 2 dictionaries in Python?

You can use the == operator, and it will work. However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to: compare two dictionaries and check how many pairs are equal.

How do you find the difference between two dictionaries?

Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second. Those keys which are not common are listed in the result set.

Can a dictionary have two keys with the same value two values with the same key?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

How to compare two dictionaries in Python and find similarities?

SO let’s start learning how to compare two dictionaries in Python and find similarities between them. Basically A dictionary is a mapping between a set of keys and values. The keys support the basic operations like unions, intersections, and differences. When we call the items () method on a dictionary then it simply returns the (key, value) pair.

How to use the keys of a dictionary?

The keys support the basic operations like unions, intersections, and differences. When we call the items () method on a dictionary then it simply returns the (key, value) pair. Now, Consider two dictionaries:

Which function is used to compare all required keys?

In this the functionality of comparison is done using all (), comparing all required keys. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

How do I combine two dictionaries in Python?

List comprehension is definitely the preferred way to do something like this so you can't go wrong reading up on it. If you're using Python 3, the keys method of dictionaries follows the set interface. That means you can do an intersection of the keys of the two dictionaries using the & operator.


1 Answers

You can try using TryGetValue:

using System.Linq;

...

var dictExcept = dict1
  .Where(pair => dict2.TryGetValue(pair.Key, out var value) && 
                 pair.Value != value)
  .ToDictionary(pair => pair.Key, 
                pair => (first: pair.Value, second: dict2[pair.Key]));

Here we for each key value pair from dict1 try to get corresponding value from dict2:

// dict2 has pair.Key it corresponds to value...
dict2.TryGetValue(pair.Key, out var value) && 
// however value from dict2 != value from dict1
pair.Value != value

The very same idea if you prefer to use foreach (no Linq solution):

var dictExcept = new Dictionary<string, (string first, string second)>();

foreach (var pair in dict1)
  if (dict2.TryGetValue(pair.Key, out var value) && value != pair.Value)
    dictExcept.Add(pair.Key, (pair.Value, value)); 

Demo: (fiddle)

  var dict1 = new Dictionary<string, string> { 
    { "a", "False" }, { "b", "False" }, { "c", "True" }, { "d", "dict1 only" } };

  var dict2 = new Dictionary<string, string> { 
    { "a", "False" }, { "b", "True" }, { "c", "False" }, { "e", "dict2 only" } };

  var dictExcept = dict1
    .Where(pair => dict2.TryGetValue(pair.Key, out var value) &&
                   pair.Value != value)
    .ToDictionary(pair => pair.Key,
                  pair => (first: pair.Value, second: dict2[pair.Key]));

  string report = string.Join(Environment.NewLine, dictExcept
    .Select(pair => $"Key: {pair.Key}; Values: {pair.Value}"));

  Console.Write(report);

Outcome:

Key: b; Values: (False, True)
Key: c; Values: (True, False)
like image 134
Dmitry Bychenko Avatar answered Oct 15 '22 15:10

Dmitry Bychenko