0

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]
imhans4305
  • 677
  • 1
  • 16
  • what you've tried? – A l w a y s S u n n y Nov 23 '22 at 17:23
  • In your own words: when you create the `word_list`, which way do you want the logic to work: do you take a value like `'r'` and look up the corresponding `'1'`? Or do you take `'1'` and look up `'r'`? Therefore, which makes more sense to use as the *key* for a lookup dictionary? Does this give you an idea how to start solving the problem? – Karl Knechtel Nov 23 '22 at 17:37

3 Answers3

2

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
1

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']
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

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']
Woodford
  • 3,746
  • 1
  • 15
  • 29
  • I think you'll find that I beat you to it with this approach :) – Karl Knechtel Nov 23 '22 at 17:42
  • @KarlKnechtel Not a very constructive (or accurate) comment... – Woodford Nov 23 '22 at 17:46
  • How isn't it accurate? I use the same techniques for both inverting the dictionary and for using the dictionary to map onto the input list; and I posted my answer first. The only thing different (aside from naming) is that I slice-assign back to the original list, because OP's attempt did that. – Karl Knechtel Nov 23 '22 at 17:50