0

How can I ensure all OrderedDicts in my dictionary have the complete set of all keys, so that a CSV can be generated from it?

So to go from this:

    unaggregated = {
        1: OrderedDict([
            ('column_a', 'foo'),
            ('column_b', 'bar'),
        ]),
        2: OrderedDict([
            ('column_a', 'baz'),
        ]),
    }

to this:

    aggregated = {
        1: OrderedDict([
            ('column_a', 'foo'),
            ('column_b', 'bar'),
        ]),
        2: OrderedDict([
            ('column_a', 'baz'),
            ('column_b', None),
        ]),
    }

I'm generating my CSV like so, perhaps I'm over complicating the data structure.

    fieldnames = next(iter(aggregated.values())).keys()
    writer = csv.DictWriter(output_file, fieldnames)
    writer.writeheader()
    for id in aggregated:
        writer.writerow(aggregated[id])

Thanks!

user2819573
  • 161
  • 1
  • 9
  • Have a look at `setdefault` (some explanation at https://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method) – Kendas Nov 23 '17 at 11:35
  • Thanks, I ended up keeping an OrderedDict of headings mapped to their order, and then reduced that at the end and ordered by that dict value. – user2819573 Nov 23 '17 at 16:25

0 Answers0