如何将带有嵌套列表的字典写入csv,并为每个嵌套值创建新行



因此,我收集了包括城市和邻里在内的数据。结果是一个关键字字典,这些关键字是城市,列表值是社区列表。例如(阿拉丘亚市,161街和110街以及94大道都是社区(:

{阿丘亚':[161st&110th Street','78th Ave/NW 218 St','94th Avenue','Brandon Estates','Clarkes Addn','Dogwood Acres','Heritage Oaks','Hunter Woods','Meadowglen','Newnansville','NW 120th Pl','NW140 St','NW 147th Ave','Oak Ridge at High Springs','Pioneer Ridge','Shaw Farms','Turkey Creek','Woodland Oaks'],'Alford':["山丘中的康帕斯湖"],"Altamonte Springs":["学院湾"、"学院橡树园"、"Altamone Springs"、"阿尔塔蒙特高地"、"阿尔塔蒙特购物中心"、"阿勒塔蒙特斯普林斯"、"苹果谷"、"巴克利森林"、"湾岬"、"布兰特利庄园"、"Brantley Terrace"、"Brookhollow"、"Bunnell/Iden Park"、"Camden Club"、"Capistrano Condo"、"Corniche Townhouses"、"Country Creek"、"Cranes Roost"、"Crescent Place"、"Emerson Plaza"、"Enclave at Altamonte"、,"Fern Park"、"Forest City"、"森林坡"、"Glen Arden Heights"、"Hailey Walk"、"Hermits Cove/Alt.Oaks"、"Hidden Ridge"、"隐泉"、"High Ridge","James town"、"Kensington Park"、,"Northlake Lilac"、"Northwood"、"Oak Harbour Condos"、"奥克兰庄园"、"奥克兰山"、"珍珠湖绿洲"、"东方花园"、"兰布尔伍德"、"Raymond Avenue South"、"River Edge"、"River Run"、"Sandy Cove"、"Sanlando"、"San Sebastian Heights"、"South Apopka"、"Spring Oaks"、"Springs Colony"、"斯普林谷"、"Sutton Place Townhouses"、"The Landings"、"Timberlake"、"Villa Brantley"、,";Waterside Crane‘s Roost"Wekiva Bend"、"Westridge Centre"、"Wymore Grove"、"Altha":["Alta Outskirts"]、"Altoona":[‘Camp Ocala’、"E Deer Rd"、"Mattison Lane"、"North Altoona"、"The Meadows"]、"Alva":[‘Alva’、"River Hall"、"Wellington"]、‘Anthony’:[‘Parr’]、"Apalachicola":["Bluff Road"、"Historic 98"]

我希望我的输出是以下格式的csv:

城市,邻里

Alachua,161st&110街

Alachua,第94大道…

因此,我想为社区列表中的每个值创建一个新行,并将城市名称保留在城市列中。我在stackoverflow和其他网站上搜索了很多问题,似乎找不到这类问题。有各种各样的方法,但没有一种与所需的输出相匹配。

例如,下面以城市为列标题,并在这些列中列出社区,但我并不搜索这些。

import itertools
keys = neighborhoods_dict.keys()
csvrows = itertools.zip_longest(*[neighborhoods_dict[k] for k in keys], fillvalue='dummy')
with open('out.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=';',
quotechar='\', quoting=csv.QUOTE_MINIMAL)
csvwriter.writerow(keys)
for row in csvrows:
csvwriter.writerow(row)

任何帮助都很感激,我一直在兜圈子。

好的,所以我设法用完成了任务

with open('try.csv', 'w') as file:
csvwriter = csv.writer(file)
csvwriter.writerow(["City", "Neighborhood"])
for key, values in neighborhoods_dict.items():
for value in values:
#             print(key, value)
row = key, value
print(row)
csvwriter.writerow(row)

这其实很简单,我只需要坐下来深呼吸,解决方案就来了。

代码中的注释

import json
import csv
#Function that takes two arguments string names of the files
def createCSV(file_json,file_csv):
#Open the data.json to fetch the data
with open(file_json) as file:
data = json.load(file)
#Create and open data.csv file to write 'w'    
with open(file_csv, "w") as file:
csv_file = csv.writer(file)
#Cre the first row names of the csv
csv_file.writerow(["City","Neighborhood "])
#Iterate the data to write them into csv file
for item in data:
for z in data[item]:
csv_file.writerow([item,z])

createCSV('data.json','data.csv')

相关内容

  • 没有找到相关文章

最新更新