简体   繁体   中英

Matching characters of a string with keys of a dictionary and converting strings to values of keys if matched

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM