'How to work around a dictionary so duplicate keys will work?

I am making a column called month which reads from an importing excel file that has a column with certain strings that represent a month number. The problem I'm currently having is that this file has different strings that represent the same month(One with letters that represent months, and another with 00 numbers that represent months). This is leading to my code to have duplicate keys.

I created a function called get_value to get the values needed and then I created the dictionary

Here is my code

def get_value(value, dictionary):
    print(dictionary.values())

    if value in dictionary.values():
        answer = [k for k, v in dictionary.items() if v == value][0]
        # answer = answer[1]
    else:
        answer = "No data"

    return answer

More code

#Dictionary to assign month letters into numbers 
month_codes = {
    "1": "F",
    "2": "G",
    "3": "H",
    "4": "J",
    "5": "K",
    "6": "M",
    "7": "N",
    "8": "Q",
    "9": "U",
    "10": "V",
    "11": "X",
    "12": "Z"
}

#Modify month column to get values from month_codes dictionary
df['Month'] = df['Month'].apply(lambda x: get_value(x,month_codes))

#New dictionary to turn 00 months in to a one digit string number
month_codes_2 = {
    "1": "01",
    "2": "02",
    "3": "03",
    "4": "04",
    "5": "05",
    "6": "06",
    "7": "07",
    "8": "08",
    "9": "09",
    "10": "10",
    "11": "11",
    "12": "12",

}

How can get both dictionaries to work for one column?



Solution 1:[1]

I am assuming your excel column can have 2 kinds of values: a string value ("Jan", "Feb", ...) and a numerical value ("01", "02", ...). What you are trying to do here is to convert them the same way (e.g. Both "Jan" and "01" should convert to 1).

If my assumption is correct, this solution may work for you. You only need one dictionary for string values ("Jan", "Feb", ...).

month_codes = {
  "Jan": 1,
  "Feb": 2,
  "Mar": 3,
  ...
}

def get_value(value, dictionary):
  try:
    return int(value)
  except Exception as e:
    return dictionary[value]

df['Month'] = df['Month'].apply(lambda x: get_value(x, month_codes))

Hope this is what you are looking for!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thu Ya Kyaw