简体   繁体   中英

How to write Dictionary AND list to csv or .xlsx with python

New to SO and programming so TIA for any help.

I have a dictionary of cities and their corresponding country. I have a list of longitudes and latitudes for each city (scraped using Selenium).

In my current code, I can only write the latitudes and longitudes to a .csv file.

Is there anyway I can write the dictionary key (city) and the corresponding long_lat, so I know what city the long_lat belongs to?

Code:

import os, time, openpyxl, csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

#IMPORT EXCEL FILE
print('opening workbook...')
os.chdir('C:\\Users\\user1\\Documents')
wb = openpyxl.load_workbook('Data.xlsx')
sheet = wb['Missing']

d = {} #dictionary to contain city and corresponding country

#GRAB CITY AND COUNTRY FROM EXCEL
for row in range(2,5):
    country = sheet['B' + str(row)].value
    city = sheet['C' + str(row)].value

    d[city] = country

lat_long_list = [['-24.211531', ' 151.902298'], ['-20.269600', ' 148.720535'], ['-43.805199', ' 172.966995']]


with open('csvPrintTest.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for coOrdinate in lat_long_list:
        writer.writerow([coOrdinate])

print('Done')    

Desired Output when opening csv in Excel:

City         LatLong

Agnes Waters  ['-24.211531', '151.902298']
Airlie Beach  ['-20.269600', ' 148.720535']
Akaroa        ['-43.805199', ' 172.966995']

Assuming your sheet are in sync with your lat_long_list , create a list of dict :

lat_long_list = [['-24.211531', ' 151.902298'], ['-20.269600', ' 148.720535'], ['-43.805199', ' 172.966995']]

csv_data = []
for row in range(2,5):
    country = sheet['B' + str(row)].value
    city = sheet['C' + str(row)].value
    i = row - 2
    csv_data.append({'city':city, 
                     'country':country, 
                     'lat':lat_long_list[i][0], 
                     'long':lat_long_list[i][1]
                    })

fieldnames = ['city', 'country', 'lat', 'long']
header = {'city':'City', 'country':'Country', 'lat':'Lat', 'long':'Long'}

with open('csvPrintTest.csv', 'w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writerow(header)
    writer.writerows(csv_data)

If your list is in the same sequence as rest of the data you can easily add it to your dictionary and then make a dataframe followed by df.to_csv('filename'). Hope it helps. Be very careful if the sequence is not the same as the rest of the lists in your dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM