Home > Software design >  split a dictionary key on ',' and replace key with new key value pairs
split a dictionary key on ',' and replace key with new key value pairs

Time:09-29

I have a dictionary that looks like {'coin-dollar' : 'money', 'banana' : 'fruit', 'carrot-pea-pepper' : 'vegetable'}. I am trying to figure out how to split the keys that have multiple words on the '-' and have each word map to the given value. I am trying to make the dictionary {'coin': 'money', dollar':'money', 'banana' : 'fruit', 'carrot': 'vegetable', pea': 'vegetable', 'pepper' : 'vegetable'}

CodePudding user response:

You can use (nested) dict comprehension with split:

dct = {'coin-dollar' : 'money', 'banana' : 'fruit', 'carrot-pea-pepper' : 'vegetable'}

output = {k: v for ks, v in dct.items() for k in ks.split('-')}

print(output)
# {'coin': 'money', 'dollar': 'money', 'banana': 'fruit', 'carrot': 'vegetable', 'pea': 'vegetable', 'pepper': 'vegetable'}

CodePudding user response:

Try:

dct = {
    "coin-dollar": "money",
    "banana": "fruit",
    "carrot-pea-pepper": "vegetable",
}

out = {kk: v for k, v in dct.items() for kk in k.split("-")}
print(out)

Prints:

{
    "coin": "money",
    "dollar": "money",
    "banana": "fruit",
    "carrot": "vegetable",
    "pea": "vegetable",
    "pepper": "vegetable",
}

CodePudding user response:

First, loop through your existing dictionary.

Then check to see if the separator exists in the key item.

Then use split to create a list of individual keys in between each of the separator items.

Finally, create a new key value pair with that updated key and return the dictionary.

def adjust_dictionary_based_on(original_dict, separator='-'):
    my_new_dictionary = dict()

    for key in original_dict:
        value = original_dict[key]

        if(str(key).find(separator) != -1):
            # if the separator is found, split into two keys
            key_list = key.split(separator)

            for each_key in key_list:
                my_new_dictionary[each_key] = value

    return my_new_dictionary

def start_program():
    mydict = {'coin-dollar' : 'money', 'banana' : 'fruit', 'carrot-pea-pepper' : 'vegetable'}

    updated_dictionary = adjust_dictionary_based_on(mydict)
    print(updated_dictionary)

start_program()
  • Related