Home > Software engineering >  How do I combine two python dictionaries and create a csv file?
How do I combine two python dictionaries and create a csv file?

Time:10-05

I have two dictionaries that contain meeting details/participants. How can combine the two dictionaries so that only the participants information is showing for both in a single .csv file?

import pandas as pd
import json

meeting1 = {
    'other': 'info',
    'participants' : [ 
        {
            'id': '123',
            'email': '[email protected]',
            'room': '1a'
        },
        {
            'id': '124',
            'email': '[email protected]',
            'room': '1a'
        }
    ]
}

meeting2 = {
    'other': 'info',
    'participants' : [ 
        {
            'id': '125',
            'email': '[email protected]',
            'room': '1b'
        }
    ]
}

particpants =  {key:[meeting1[key], meeting2[key]] for key in meeting1}


print(particpants)
 
json_object = json.dumps(particpants) 
print(json_object)

df = pd.read_json(json_object)
df.to_csv('participants.csv')

here is my current output in the .csv file:

other,participants
info,"[{'id': '123', ... 'room': '1a'}, {'id': '124', ... 'room': '1a'}]"
info,"[{'id': '125', ... 'room': '1b'}]"

and here is what I'm trying to get in the .csv file:

id, email, room
123, 1@email.com, 1a
124, 2@email.com, 1a
125, 3@email.com, 1b

CodePudding user response:

Here a solution using pandas only.

df = pd.concat(
    [pd.DataFrame(meeting1["participants"]),
     pd.DataFrame(meeting2["participants"])],
    ignore_index=True)

output

    id        email room
0  123  [email protected]   1a
1  124  [email protected]   1a
2  125  [email protected]   1b

And you can save to csv using df.to_csv("file.csv")

CodePudding user response:

You can do this without pandas or json.

import csv

meeting1 = {
    'other': 'info',
    'participants' : [ 
        {
            'id': '123',
            'email': '[email protected]',
            'room': '1a'
        },
        {
            'id': '124',
            'email': '[email protected]',
            'room': '1a'
        }
    ]
}

meeting2 = {
    'other': 'info',
    'participants' : [ 
        {
            'id': '125',
            'email': '[email protected]',
            'room': '1b'
        }
    ]
}

# Create a dictionary mapping the participant ID, which I assume is unique
# to the participant details
# That participants in both meetings are not duplicated
all_participants = {p["id"]: p for mtg in (meeting1, meeting2) for p in mtg["participants"] }

with open("out.csv", "wt", newline="") as fd:
    wrtr = csv.DictWriter(fd, fieldnames=["id", "email", "room"})
    wrtr.writeheader()
    wrtr.writerows(all_participants.values())
  • Related