以特定模式排列列表项

Amy*_*yth 0 python dictionary list

我希望实现的是以特定模式排列列表中的项目.说,我有以下字典:

>>>dict_a = {
       'north' : 'N',
       'south' : 'S',
       'east' : 'E',
       'west' : 'W',
       'north east' : 'NE',
       'north west' : 'NW'
   }
Run Code Online (Sandbox Code Playgroud)

现在检查字符串是否包含上述字典中的任何项目:

>>>string_a = 'North East Asia'
>>>list_a = []
>>>for item in dict_a:
       if item in string_a.lower():
           list_a.append(item)
Run Code Online (Sandbox Code Playgroud)

它给我的结果如下,这是有道理的

>>>['north', 'north east', 'east']
Run Code Online (Sandbox Code Playgroud)

但我想得到的是['north east'],忽略northeast.我怎么做到这一点?

Abh*_*jit 5

尝试difflib.closest_match

>>> dict_a = {
       'north' : 'N',
       'south' : 'S',
       'east' : 'E',
       'west' : 'W',
       'north east' : 'NE',
       'north west' : 'NW'
   }
>>> import difflib
>>> string_a = 'North East Asia'
>>> dict_a[difflib.get_close_matches(string_a, dict_a.keys())[0]]
'NE'
Run Code Online (Sandbox Code Playgroud)