Samer
Samer

Reputation: 687

Save multiple dict values to a single csv row

I have the following file, created as defaultdict(lambda: defaultdict(dict))

{
 food_type1{
            brand1: a
            brand3: b
            }
 food_type2{
            brand1: c
            brand2: d
            brand3: e
            brand4: f
            }
 food_type3{
            brand2: g
            }
}

I also create the CSV header from a list, like this one: "food_type", "brand1", "brand2", "brand3", "brand4"

The dictionary can't be changed, it needs to have that scructure, but I can change the header list to something more appropiate (such as a dict) if needed.

I want to create a CSV file with the defined header from the list and then assign the values from the dictionary to the corresponding keys for each food_type, as follows:

"food_type",  "brand1", "brand2", "brand3", "brand4"
"food_type1", "a",       "",      "b",      ""
"food_type2", "c",       "d,",    "e",      "f"
"food_type3", "",        "g",     "",       ""

I've tried for brand in food_type loops but that creates a new row for each brand, and it's not what I'm looking for. I need to have all the relative information to a certain food_type in the same row and with the required order.

How can I achieve this?

Upvotes: 0

Views: 933

Answers (1)

wilfo
wilfo

Reputation: 715

Assuming you know each key in the dictionary belongs to the food_type column, you could try the following script using csv.DictWriter and some dict comprehension:

import csv

data = {
   "food_type1":{
              "brand1": "a",
              "brand3": "b"
              },
   "food_type2":{
              "brand1": "c",
              "brand2": "d",
              "brand3": "e",
              "brand4": "f"
              },
   "food_type3":{
              "brand2": "g"
              }
  }

headers = ["food_type",  "brand1", "brand2", "brand3", "brand4"]

with open("/tmp/test.csv", "w") as f:
    dict_writer = csv.DictWriter(f, headers, delimiter=',')
    dict_writer.writeheader()

    rows = []

    for key, row in data.iteritems():
        d = {header: row[header] if header in row else "" for header in headers}
        d["food_type"] = key
        rows.append(d)

    for row_dict in rows:
        dict_writer.writerow(row_dict)

Upvotes: 1

Related Questions