Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to compare two dictionary values?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading