Home > Software engineering >  Trying to cross map 2 dictionaries together, Python
Trying to cross map 2 dictionaries together, Python

Time:06-02

I am trying to do a bit of data transformation using Python dicts.

dict1 = {'email1':'id1', 'email2': 'id2', ..}

dict2 = {'abbreviation': ['email1', 'email2', 'email3', ..], 'abbreviation2': ['email2', 'email3', 'email4', ...], ...}

What I want to do is a dict which will have something like this as output:

result = {'abbreviation': [id1, id2, ...]}

I have tried

needed_ids = dict()
temp_list = list()

for email, id in dict1.items():
    for abbrev, list_of_emails in dict_results.items():
        if email in list_of_emails:
            # Get the abbreviation of the language
            temp_lst.append(id)
            needed_ids[abbrev] = temp_lst

This gave me only 1 value in the temp list and not all the ids values. Any hints please?

Thank you

CodePudding user response:

Your code is almost correct you just need to change one part so that it looks like this

needed_ids = dict()

for email, id in dict1.items():
    for abbrev, list_of_emails in dict2.items():
        if email in list_of_emails:
            # Get the abbreviation of the language
            current_ids = needed_ids.get(abbrev,[])
            current_ids.append(id)
            needed_ids.update({abbrev:current_ids})

In this version you are getting the ids of the current abbrev or if there are none it returns an empty list. you then append to that list and place it back into the dictionary using the update function

CodePudding user response:

You need to iterate over the emails list in dict2 and get the matching id from dict1

dict1 = {'email1':'id1', 'email2': 'id2'}
dict2 = {'abbreviation': ['email1', 'email2', 'email3'], 'abbreviation2': ['email2', 'email3', 'email4']}

needed_ids = dict()

for abbrev, list_of_emails in dict2.items():
    for email in list_of_emails:
        if email in dict1:
            needed_ids[abbrev] = needed_ids.get(abbrev, [])   [dict1[email]]

You can also convert it to dict comprehensions if you like

needed_ids = {abbrev: [dict1[email] for email in list_of_emails if email in dict1]
              for abbrev, list_of_emails in dict2.items()}

Output:

{'abbreviation': ['id1', 'id2'], 'abbreviation2': ['id2']}
  • Related