简体   繁体   English

如何使用python将Dictionary AND list写入csv或.xlsx

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

New to SO and programming so TIA for any help. SO和编程的新手,所以TIA可以提供任何帮助。

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. 在当前代码中,我只能将纬度和经度写入.csv文件。

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? 无论如何,我可以写字典键(city)和相应的long_lat,所以我知道long_lat属于哪个城市吗?

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: 在Excel中打开csv时所需的输出:

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 : 假设工作sheetlat_long_list同步,则创建dict list

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'). 如果列表的顺序与其余数据的顺序相同,则可以轻松地将其添加到字典中,然后创建一个数据框,后跟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. 如果序列与字典中其余列表的序列不同,请非常小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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