Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - How to show nested dictionaries in CSV file

I have dynamics field and I need the CSV file shows field in its column, you can see in this image, the dynamic fields shows literals {} brackets and show all of them in one row, enter image description hereI need to separte in each column I don't care if father header is duplicate for each dynamic field (JOB_INSIGHTS FOR INSTANCE). I want every nested dict element in its own column. Thanks in advance!!

updating: the output plicated got with the following code: dict example:

my_list_didct= [{
    "main_rating": "7",
    "job_salary": "$51K",
    "job_insights": {
        "Job Type : ": "Full-time",
        "Job Function : ": "Software Developer",
    "aditional_salaries":{"dev_ops":"$44k",
                          "sysadmin":"$30k"}
    }]


    try:
        ruta_guardado = os.path.join(out_path_file,
                                     'file_{today.strftime('%d-%m-%Y')}_{readfrom_text_file('dat')}.csv")
        with open(
                ruta_guardado, mode, newline='', encoding='utf-8') as file:
            csv.register_dialect('myDialect',
                                 delimiter=';',
                                 quoting=csv.QUOTE_ALL)
            print(items)
            headers = list(items[0].keys())
            csv_writer = csv.DictWriter(file, fieldnames=headers, dialect="myDialect")
            csv_writer.writeheader()
            my_logger.info(items)
            csv_writer.writerows(items)

in the example on top aditional salaries is not always found, sometimes return empty dict, in that case I would like a excel field empty. or if exists spread like the rest of fields which are str instead a dict. :L thank you coders.

kind of output I'm looking for. enter image description here

question from:https://stackoverflow.com/questions/65713732/how-to-show-nested-dictionaries-in-csv-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, You can't save a dict into into .csv file without converting it into a DataFrame. So, you need to convert it into a DataFrame then save it into whatever file you want to save

Also, if you don't have a file and you just write the name and the format of the file, it will immediately save it.

Code Syntax

import pandas as pd

my_list_didct= [{
    "main_rating": "7",
    "job_salary": "$51K",
    "job_insights": {
        "Job Type : ": "Full-time",
        "Job Function : ": "Software Developer",
    "aditional_salaries":{"dev_ops":"$44k",
                          "sysadmin":"$30k"}
    }}]

df = pd.DataFrame(my_list_didct)
df.to_csv('file.csv', index=False)

Output enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...