Add same key and values while for loop in python dictionnary

Viewed 81

I am a python beginner and I am working on a small project but I can't get the output wanted.

This is the entry value that I have, I have to keep only the email's and associate them with the project without duplicated values. This my entry:

my_dictionnary = [
    {
        "email": ["email1", "email2"],
        "project":"projet1",
        "project_name":"Project1"
    },
    {
        "email": ["email1", "email2"],
        "project":"projet2",
        "project_name":"Project2"

    },
    {
        "email": ["email2"],
        "project":"projet3",
        "project_name":"Project3"

    }
]

I would like to create the ouput as follows:

my_dictionnary_parsed = {
    "email2": ["projet1", "projet2", "projet3"],
    "email1": ["projet1", "projet2"]
}

I have the following function:

def formating_email(list_of_email):
    dictionnary={}
        for email_data in list_of_email_data:
            for cp in email_data['cp_related']:
                print(cp,email_data['ticket_related_project'])
                dictionnary[cp] = email_data

But the values keep overriding...

2 Answers

You can use defaultdict

from collections import defaultdict

new_dict=defaultdict(list)

for d in my_dictionnary:
    proj_name=d['project']
    for email in d['email']:
        new_dict['email'].append(proj_name)

defaultdict(list,
            {'email1': ['projet1', 'projet2'],
             'email2': ['projet1', 'projet2', 'projet3']})

Assuming you have correct dictionary structure, because the current one is incorrect, you are directly setting the dictionnary[cp] = email_data. You should instead append because it is a list.

Also, do not name your variables as dictionnary. Give them some valid names that correspond to their functionality, such as projects_per_email or anything else.

def formating_email(list_of_email):
    dictionnary={}
        for email_data in list_of_email_data:
            for cp in email_data['cp_related']:
                print(cp,email_data['ticket_related_project'])
                if dictionnary.get(cp) == None:
                    dictionnary[cp] = [email_data]
                else:
                    dictionnary[cp].append(email_data)
Related