imhans4305
imhans4305

Reputation: 697

Replacing character in a list with keys from a dictionary of lists

I have a dictionary containing lists like

char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}

I have another list containing characters

word_list = ['r', 'v', 'p', 'c']

I want to replace the letters in word_list with keys in the dictionary so that it should become

['6', '1', '1', '2']

I tried some thing like

word_list[:]=[char_code.get(e,'') for e in word_list]

Upvotes: 0

Views: 35

Answers (3)

Woodford
Woodford

Reputation: 4449

Your dictionary isn't structured efficiently to do the kind of lookup you're asking for - it's "inside out". You can do it, but it's clumsy. You want the key to be a letter and it's value to be the code, but you have the other way around.

Transform your dictionary and it will simplify your list creation:

>>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst}
>>> [letter_to_code[letter] for letter in word_list]
['6', '1', '1', '2']

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61625

First, invert the dictionary, so that you can easily look up the digit symbol for a given letter:

num_code = {
    letter: digit
    for digit, letters in char_code.items()
    for letter in letters
}

Then simply use that lookup to do the mapping:

word_list[:] = [num_code[letter] for letter in word_list]

Which gives us the expected result.

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

One way to do it with for looping on word_list and using list comprehension to find each list element inside char_codedictionary and finallyappend` the keys like this-

char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}

word_list = ['r', 'v', 'p', 'c']
expected_list = []
for word in word_list:
    expected_list.append([k for k, v in char_code.items() if word in v][0])
print(expected_list)

Output:

['6', '1', '1', '2']

Upvotes: 1

Related Questions