defaultdict

from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
     d[k].append(v)
d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

flatten nested list

flat_list = [item for sublist in l for item in sublist]

dedupliate list

seen = set()
[i for i in l if not (i in seen or seen.add(i))]

ABCmeta & abstractmethod

TODO

write/read excel

write

from openpyxl import Workbook

data = [
    ['id', 'username', 'mobile'],
    [1, 'lily', '138000000'],
    [2, 'jim', '139000000'],
]

wb = Workbook()
ws = wb.active
for row in data:
    ws.append(row)
wb.save(filename='data.xlsx')

read

from openpyxl import load_workbook

wb = load_workbook(filename = 'empty_book.xlsx')
sheet_ranges = wb['range names']
print(sheet_ranges['D18'].value)

write/read csv

write list of dict to csv

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)