I am to compare values of dictionary and find if they are congruent like so;
If the dict is {‘k1′:’v2′,’k2′:’v2′,’k3′:’v2’} i want to compare values which are all identical in this case and for python to print Three values are the same
The code i am currently using gives me a list of duplicated elements which is no good.
CODE:
d1={'k1':'v2','k2':'v2','k3':'v2'}
l=[]
for v in d1.keys():
for c in d1.keys():
if d1[v] == d1[c]:
l.append(c)
if len(l)==0:
print('No keys have same values!')
else:
print(l)
Thanks in advance
>Solution :
If you are looking to see if all of the values of a dictionary are the same, then you could do something like:
d1 = {"k1": "v2", "k2": "v2", "k3": "v2"}
if len(set(d1.values())) == 1:
print("All values are the same")
Explanation: d1.values() contains all of the values, set() de-duplicates it, and len() provides the length. If there is only 1 de-duplicated value, then all of the values must be the same.
If you are looking specifically for the count of values that are the same (even when they are not all the same, then you could use a variation of this, comparing the number of de-duplicated values to the number of keys.