Home > Back-end >  Raise an error when a key is duplicated in a dictionary
Raise an error when a key is duplicated in a dictionary

Time:05-07

I've created a code that reads in a text file and converts the lines to a dictionary.

How do I raise an error if there is more than one key with the same value? I don't know the value of the particular keys so I need it to check the values itself. Currently it is overwriting the key-value but I would like to know how to check the dictionary keys against each other so i can raise an error message. Thank you

CodePudding user response:

d={"key":"val"} #some dictionary
if len(set(d.values())) != len(d.values()):
    raise ValueError("Your error")

CodePudding user response:

Can you also post the input file and/or the code you are using to create the dictionary? As Steve is also implying through his questions, it might be better to solve the root of the problem rather than simply flag the issue.

For example, it might be helpful to know the value of the keys that are are causing the issue and treat them in some specific way rather than just overwriting. For this, if you are using something like the below code to create your dictionary:

my_dictionary = dict(keys, values)

You can use:

import pandas as pd
key_srs = pd.Series(keys)
key_counts = key_srs.groupby(key_srs).count()
duplicate_key_counts = key_counts[key_counts>1]

To find the duplicate keys and how many times they have been repeated.

  • Related