Denormalizing an OrderedDict to CSV Cross post from stackoverflow, as suggested.

I have an ordereddict, and I need to store it in CSV file.
Input:

dic = collections.OrderedDict([('k1', 'v1'),
                               ('k2', 'v2'),
                               ('k3', [ [('k3a',21), ('k3b',22)],
                                        [('k3a',23), ('k3b',24)] ]),
                               ('k4', [1,2,3,4])])

mapping = {'k3': ['k3a', 'k3b']}


Desired output:

k1,k2,k3a,k3b,k4
v1,v2,21,22,1
v1,v2,23,24,2
v1,v2,,,3
v1,v2,,,4


That is, substitute the top level keys in the mapping dictionary with the sub-keys in the OrderedDict, and add blank fields when no data is available.

My working code so far is:

import csv
import collections

max_len = 0
result = []
for k,v in dic.items():
    if isinstance(v, list) and len(v) &gt; max_len:
        max_len = len(v)

for i in range(max_len):
    tmp = collections.OrderedDict()
    for k, v in dic.items():
        if not isinstance(v, list):
            tmp.update({k:v})
        else:
            if k in mapping and i &lt; len(v):
                if isinstance(v[i], list):
                    for tup in v[i]:
                        tmp.update({tup[0]:tup[1]})
            elif k in mapping and i &gt;= len(v):
                for mk in mapping[k]:
                    tmp.update({mk:''})
            else:
                try:
                    tmp.update({k:v[i]})
                except IndexError:
                    tmp.update({k:''})
    result.append(tmp)

with open("out.csv", "w", newline='') as csvfile:
    writer = csv.DictWriter(csvfile, result[0].keys())
    writer.writeheader()
    writer.writerows(result)


Is there a cleaner/easier way to achieve the desired result?
tmp.update({k:v}) is an unusual way to perform tmp[k] = v
Take advantage of the max builtin:

max_len = max(len(v) for v in dic.values() if isinstance(v, list))

To make the code easier to follow, you could first transform the dictionary to give it a consistent structure like this

{'k1': ['v1', 'v1', 'v1', 'v1'],
 'k2': ['v2', 'v2', 'v2', 'v2'],
 'k3a': [21, 23],
 'k3b': [22, 24],
 'k4': [1, 2, 3, 4]}                


using code like this

mapped = collections.OrderedDict()
for key, value in dic.items():
    if key in mapping:
        for sublist in value:
            for subkey, subvalue in sublist:
                mapped.setdefault(subkey, []).append(subvalue)
    elif isinstance(value, list):
        mapped[key] = value
    else:
        mapped[key] = max_len * [value]

Then you can take advantage of itertools.zip_longest to produce the output:

with open("out.csv", "w", newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(list(mapped.keys()))
    writer.writerows(itertools.zip_longest(*mapped.values(), fillvalue=''))