Home > Enterprise >  Matching characters of a string with keys of a dictionary and converting strings to values of keys i
Matching characters of a string with keys of a dictionary and converting strings to values of keys i

Time:11-18

I have a dictionary of my_dict={'A':1, 'B':1,'C':1,'D':2,'E':2,'F':2,'G':3,'H':3,'I':3} I would like to write a function that inputs a string and if the length is 5, checks characters of the string with the keys of the dictionary and if matching, prints values of those keys, else should return false. For instance, if I input a string of "ABIFA", it should produce 11321. Below is my code, but it does not produce what I expect:

my_dict={'A':1, 'B':1,'C':1,'D':2,'E':2,'F':2,'G':3,'H':3,'I':3}



def string_to_number(mystring):
    
    if len(mystring)==5:
        
        result = [val for key, val in my_dict.items() if mystring in key]
    
        print(str(result))
    
    else:
        return False
    
    
string_to_number("ABIFA") # should produce 11321

string_to_number("ABIFAA") # should return False

Could you tell me where I make a mistake, please?

CodePudding user response:

You can map each key/value result to a str and then join using a generator expression

def string_to_number(mystring):
    if len(mystring) == 5:
        return ''.join(str(my_dict[i]) for i in mystring)
    else:
        return False
  • Related