import csv from collections import defaultdict by_country = defaultdict(lambda: []) with open("worldcities.csv") as infile: reader = csv.reader(infile, delimiter=",", quotechar='"') next(reader) # skip header for _, name, lat, lng, _, iso2, *_ in reader: by_country[iso2].append((iso2.lower(), name, lat, lng)) with open("urban-centers.csv", "w") as outfile: for k, v in by_country.items(): csv.writer(outfile, delimiter=",", quotechar='"').writerows(v)