There is a dictionary:

d = {'a': '1', 'b': '2', 'c': '3'} 

and there is a line:

 stroka = 'a3a2c' 

If the string element is among the dictionary values, you must output the key that corresponds to the value. If among the keys, then output the value by key value. Output must be in two lines, the values ​​are separate from the keys.

 Т.е. для строки 'a3a2c' ожидаемый вывод '113' и 'cb' 

How to display values ​​by key - I figured out:

 for i in stroka: if i in d.keys(): print(d[i], end='') 

But I can't get the key by value:

 for j in stroka: if j in d.values(): print(?????, end='') 

    6 answers 6

    Something like this:

     d = { 1: '1', '2': 2, 3: '3', } def get_key(d, value): for k, v in d.items(): if v == value: return k print(get_key(d, '1')) print(get_key(d, 2)) print(get_key(d, 42)) 

    Console:

     1 2 None 

    Generally, when I need to get a value by key and key by value, I start two dictionaries.

    • You can invert the dictionary inv_d = {value: key for key, value in d.items()} and once again output the value by key. But maybe there is another way? Something can be substituted into the print in my case? - Sergey Mokhin
    • one
      The get_key function, for example. Or using an inverted dictionary: for k in inv_d: print(inv_d[k]) . Here we will have the value of the original dictionary in k and accordingly, we will receive and display keys by values - gil9red

    Those. for the string 'a3a2c' the expected output is '113' and 'cb'

    If there is a dictionary d and a collection of keys , then to get the corresponding values, use the default values ​​for the missing keys:

     def get_values(d, keys, default=None): return (d.get(k, default) for k in keys) 

    Example:

     d = {'a': '1', 'b': '2', 'c': '3'} s = 'a3a2c' print(''.join(get_values(d, s, ''))) # -> 113 inv_d = dict(zip(d.values(), d.keys())) print(''.join(get_values(inv_d, s, ''))) # -> cb 

    If you want to immediately filter the missing keys:

     def get_existing_values(d, keys): return filter(None, map(d.get, keys)) 

    Example:

     >>> ''.join(get_existing_values(inv_d, s)) 'cb' 
       d=dict(a='1',b='2',c='3') # первый словарь print(d) stroka = 'a3a2c' print('stroka=',stroka) for m in stroka: #поиск элементов из stroka в ключах d if m in d.keys(): #вывод значений этих лючей print('буква ', m, 'из строки "stroka" является ключом значения ', d[m]) s=[] for i in d.keys(): #второй s.append((d[i],i)) #словарь b=dict(s) #является обратным для первого #значения являются ключами, а ключи значениями stroka_=stroka for i in stroka_: #поиск элементов из stroka в значениях d if i in b.keys(): #вывод ключей этих значений print('цифра ', i, 'из строки "stroka" является значением ключа', b[i]) 

      But the task would be a little more interesting if the representation of the values ​​of the dictionary were not lower-case, but integer.

        For dictionary {'a': 1, 'b': 2, 'c': 3} (dictionary values ​​are elements of type int)

         d=dict(a=1,b=2,c=3) # первый словарь print(d) stroka = 'a3a2c' print('stroka=',stroka) for m in stroka: #поиск элементов из stroka в ключах d if m in d.keys(): #вывод значений этих лючей print('буква ', m, 'из строки "stroka" является ключом значения ', d[m]) s=[] for i in d.keys(): #второй s.append((d[i],i)) #словарь b=dict(s) #является обратным для первого #значения являются ключами, а ключи значениями stroka_=stroka #stroka_ = 'a3a2c' #поиск элементов из stroka в значениях d #вывод ключей этих значений v=','.join(str(b.keys())) #v=d,i,c,t,_,k,e,y,s,(,[,1,,, ,2,,, ,3,],) s_=[] for i in v: try: s_.append(int(i)) except ValueError as e: continue # s_= [1, 2, 3] i=0 while i < len(s_): s_[i]=str(s_[i]) i+=1 # s_= ['1', '2', '3'] #поиск элементов из stroka в значениях d #вывод ключей этих значений for i in stroka_: #stroka_ = 'a3a2c' if i in s_: # s_= ['1', '2', '3'] print('значение', stroka_[stroka_.index(i)], 'из строки "stroka" является значением ключа', b[int(i)]) 
           for key in a: print ("%s -> %s" % (key, a[key])) #python3 

            solved your problem a little differently.

            just turn the dictionary keys into tuple using the list() method and save it in a new variable, then call the key values ​​and save it in a variable, and at the end you can

             print(переменная_1[индекс ключа которую вы сохранили], переменная_2[индекс ключ] 
            • Sorry make a list with the list () method - rifkat makhmudov