Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding duplicate values in dictionary and print Key of the duplicate element

What can be the fastest way to to check the duplicate values in the dictionary and print its key?

Dictionary MyDict which is having following values,

Key Value

22 100

24 200

25 100

26 300

29 200

39 400

41 500

Example: key 22 and 25 have same values and i need to print that 22 and 25 have duplicate values.

like image 836
Sangram Nandkhile Avatar asked Aug 24 '11 08:08

Sangram Nandkhile


People also ask

Can key in dictionary have duplicate values?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can dictionary have duplicate key values python?

Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list.

Can dictionary have duplicate keys Java?

keys cannot be duplicate by definition.


1 Answers

It depends. If you have an ever changing dictionary and need to get that information only once, use this:

MyDict.GroupBy(x => x.Value).Where(x => x.Count() > 1)

However, if you have a dictionary that is more or less static and need to get this information more than once, you should not just save your data in a Dictionary but also in a ILookup with the value of the dictionary as the key and the key of the dictionary as the value:

var lookup = MyDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);

To print the info, you can use the following code:

foreach(var item in lookup)
{
    var keys = item.Aggregate("", (s, v) => s+", "+v);
    var message = "The following keys have the value " + item.Key + ":" + keys;
    Console.WriteLine(message);
}
like image 76
Daniel Hilgarth Avatar answered Oct 21 '22 12:10

Daniel Hilgarth