Skip to content
Advertisement

how to match the keys of a dictionary and return their values?

I have two dictionaries:

x= {'албански': 'Albanian', 'елзаски': 'Alsatian', 'арагонски': 'Aragonese', 
'арберешки': 'Arberesh'}

y={'елзаски': 477, 'арагонски': 0, 'арберешки': 1,'албански': 1}

Both dictionaries contains the same amount of key_value pairs. In dictionary x, the key is the translation in Bulgarian of names of languages and the values are the names of the same languages in English.

in dictionary y, the keys are the name of the languages in Bulgarian and the values are their frequency counts.

All languages present in Dic x are present in dic y, but they are in different orders.

What I need to do is to return the names of the languages in English and their corresponding counts. For this I first need to search for the keys in dic x in dic y and when they match return the values in x and values in y. How to do this?

I have tried the following code, but does not work and even if it worked I think I would not get what I need.

x=dict(zip(lang_lists['languages_bulgarian'],lang_lists['languages_english']))
y=dict(zip(lang_lists['report_lang_list'], lang_lists['counts']))

for i in x:
  for j in y:
    if j == y:
      print(x[i], y[j])
    else:
      pass

My idea was to search the corresponding keys between the two dictionarys and when they match return the values of one dictionary (languages in English) and the values in the other dictionary (frequency counts). my desired output is something like:

{Albanian: 1, Aragonese: 0, Arberesh: 1, Alsatian: 477}

Advertisement

Answer

using dict comprehension

x = {'албански': 'Albanian', 'елзаски': 'Alsatian', 'арагонски': 'Aragonese', 
'арберешки': 'Arberesh'}

y = {'елзаски': 477, 'арагонски': 0, 'арберешки': 1,'албански': 1}

result = {value:y.get(key) for key, value in x.items()}
print(result)

output

{'Albanian': 1, 'Alsatian': 477, 'Aragonese': 0, 'Arberesh': 1}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement