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.
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list.
keys cannot be duplicate by definition.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With