There are two dictionaries:

dict_1 = {'Петя Петров':0, 'Иван Иванов': 0, 'С.C. Сидоров': 0} dict_2 = {'Петров': 1, 'Иванов': 2, 'Шпак':3} 

It is necessary to write the values ​​from dict_2 into the corresponding values ​​of dict_1. If in the first dictionary there is no corresponding key, you need to inform about it. Upon learning that in the if / else construct, the words if and else do not have to be with equal indents, I tried to write the following code:

 for k_2 in dict_2: for k_1 in dict_1: if k_2 in k_1: dict_1[k_1] += dict_2[k_2] break else: print(k_2, 'не найден') print(dict_1) 

Result:

 Шпак не найден {'Петя Петров': 1, 'Иван Иванов': 2, 'С.C. Сидоров': 0} 

It seems to work. I want to know the opinion of professionals, does this code have a right to exist? What are other ways to solve my problem?

  • one
    dict((k1,dict_2[k2]) if k2 in k1 else (k1, 'не найден') for k1, k2 in zip(dict_1, dict_2)) - Igor Igoryanych
  • if k_2 in k_1: Here you will check if the key from the first dictionary is included in the name of the second dictionary key. Ie if in the second dictionary there is a key 'P', and in the first one there is a key 'Peter Petrov', then all the same your code will pass through and will not give out 'not found'. Do you need it? Or do you need the keys from the dictionaries to completely match? - Dimabytes
  • In dict_2 can only occur surnames (a word in the second position)? - MaxU
  • @Dimabytes, it is necessary that the key from the second dictionary is included in the name of the key of the first dictionary. They should not completely coincide. - Agio
  • @MaxU, optional. The first dictionary can contain keys in the form of 'first name last name' or 'last name first name' - Agio

2 answers 2

Attempting to rewrite the algorithm resulted in more lines and a decrease in sugar content, in general, a controversial decision:

 for k_2 in dict_2: found = False for k_1 in dict_1: if k_2 in k_1: dict_1[k_1] += dict_2[k_2] found = True break if not found: print(k_2, 'не найден') 

    You can make the conditions in a separate dictionary of correspondences, when you create it, you can “tie” the more extensive logic:

     # -*- coding: utf-8 -*- dict_1 = {'Петя Петров':0, 'Иван Иванов': 0, 'С.C. Сидоров': 0} dict_2 = {'Петров': 1, 'Иванов': 2, 'Шпак': 3} dict_3 = dict([(k1, k2) for k2 in dict_2 for k1 in dict_1 if k2 in k1]) for k in dict_1: try: print dict_2[dict_3[k]] except KeyError: print 'для ', k, 'значение не найдено' 
    • ...не думайте о мнении профессионалов... usually always helpful to know the opinions of colleagues :) - gil9red
    • ATP, did not immediately understand what the author wanted - Eugene Dennis