2011/06/10

Join multiple dictionary and flatten joined list in Python2

import random
import csv

def flatten(L):
if isinstance(L, list):
return reduce(lambda a,b: a + flatten(b), L, [])
else:
return [L]

def main():
dict1 = {}
for i in range(0,100,2):
dict1[i] = [random.random(),random.random()]
dict2 = {}
for i in range(0,100,3):
dict2[i] = [random.random(),random.random()]
dict3 = {}
for i in range(0,100,5):
dict3[i] = [random.random(),random.random()]

f = open("./test.csv", "a")
writer = csv.writer(f)

for k1,v1 in dict1.items():
if k1 not in dict2:
continue
if k1 not in dict3:
continue
v2 = dict2[k1]
v3 = dict3[k1]

l = []
l.append(k1)
l.append(v1)
l.append(v2)
l.append(v3)
writer.writerow(flatten(l))

if __name__ == "__main__":
main()

No comments:

Post a Comment

100