Python. Best way to match dictionary value if condition true
<p>I'm trying to build a parser now part of my code is looks like this:</p>

<pre><code>    azeri_nums      = {k:v for k,v in zip(range(1,10),("bir","iki","uc","dord","beÅ","altÄ±","yeddi","sÉkkiz","doqquz"))}
russian_nums    = {k:v for k,v in zip(range(1,10),("Ð¾Ð´Ð¸Ð½","Ð´Ð²Ð°","ÑÑÐ¸","ÑÐµÑÑÑÐµ","Ð¿ÑÑÑ","ÑÐµÑÑÑ","ÑÐµÐ¼Ñ","Ð²Ð¾ÑÐµÐ¼Ñ","Ð´ÐµÐ²ÑÑÑ"))}
</code></pre>

<p>Imagine that I should find the digit if roomnum ="Ð¾Ð´Ð½Ð°"
Here is how I trying to match this:</p>

<pre><code>    if roomnum.isalpha():
    for key,value in azeri_nums.items():
        if value.startswith(roomnum.lower()):
            roomnum = str(key)
            break

if roomnum.isalpha():
    for key,value in russian_nums.items():
        if value.startswith(roomnum.lower()):
            roomnum = str(key)
            break
</code></pre>

<p>is there any other method to do that that will work faster, or some best practices for this situation?</p>

<p>Thank you in advance!</p>

<p>P.S.
the reason that this code works that module "re" capture from "Ð¾Ð´Ð½Ð°" only "Ð¾Ð´" and that is why "Ð¾Ð´Ð¸Ð½".startswith("Ð¾Ð´") returns true.</p>

<p>Change your dict to be</p>

<pre><code>azeri_nums = {v.lower():k for k,v in zip(range(1,10),("bir","iki","uc","dord","beÅ","altÄ±","yeddi","sÉkkiz","doqquz"))}
russian_nums  = {v.lower():k for k,v in zip(range(1,10),("Ð¾Ð´Ð¸Ð½","Ð´Ð²Ð°","ÑÑÐ¸","ÑÐµÑÑÑÐµ","Ð¿ÑÑÑ","ÑÐµÑÑÑ","ÑÐµÐ¼Ñ","Ð²Ð¾ÑÐµÐ¼Ñ","Ð´ÐµÐ²ÑÑÑ"))}
</code></pre>

<p>And once you've names mapped to digits, just use:</p>

<pre><code>key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
    key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
    key = russian_nums[roomnum_lower]
</code></pre>

<p>Dictionary is based on keysearch, not valuesearch. The first one is O(1) and allows u to use <code>key in dict</code> when the 2nd one is O(n) and requires looping.</p>

<h1>EDIT TO COMMENT:</h1>

<p>if you want to map one word to others, create another dict that will handle it.</p>

<pre><code> string_map = {'Ð¾Ð´Ð½Ð°': ['Ð¾Ð´Ð¸Ð½',]} # map single string to many others if u want
</code></pre>

<p>And then all u need to do is:</p>

<pre><code>key = None # By default
roomnum_lower = roomnum.lower()
if roomnum_lower in azeri_nums:
    key = azeri_nums[roomnum_lower]
elif roomnum_lower in russian_nums:
    key = russian_nums[roomnum_lower] 
if key is None:
    # At this point you know that the single string is not in any dict,
    # so u start to check if any other string that u assigned to it is in dict
    for optional_string in string_map.get(roomnum_lower, []):
        opt_str_low = optional_string.lower()
        key = azeri_nums.get(opt_str_low, None)
        key = russian_nums.get(opt_str_low, None) if key is None else key
</code></pre>

python dictionary