gpt4 book ai didi

python - 用csv写两个字典

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:19 24 4
gpt4 key购买 nike

您好,我需要将两个词典写入一个 csv,我想按顺序编写第一个词典,而第二个词典的顺序无关紧要,第二个字典的键是来自 selenium 驱动程序的 cookie,因为我不知道每个站点将返回多少个键(每个网站都不同)

user1= {'ID':1,'Name':'John','Age':13} # the order I want to keep those must come first
cookies_data = driver.get_cookies() # dictionary
with open('file.csv','w') as csvFile:
#write to file in this order id,name,age,cookies


# A sample of cookies:
#cookies_data = [{'domain': 'google.com', 'expiry': 1624301720.007404, 'httpOnly': True, 'name': 'ANID', 'path': '/',}]
#cookies_data can have more than one dictionary and some of the keys may be the same

最佳答案

您可以使用 csv.DictWriter编写您的 csv,从组合字典中选择列的名称和值,并使用它们编写 csv,同时遍历 cookies_data 列表

#Combine fieldnames of both dictionaries
fieldnames = list(user1.keys()) + list(cookies_data[0].keys())

#Open csv file
with open('file.csv','w') as csvFile:

#Write the header and write the combined dictionary
writer = csv.DictWriter(csvFile, fieldnames=fieldnames)
writer.writeheader()

#Loop over the cookies_data list and write the combined dict to csv
for data in cookies_data:
new_dict = {**user1, **data}
writer.writerow(new_dict)

输出将是

ID,Name,Age,domain,expiry,httpOnly,name,path,secure,value
1,John,13,.....
1,John,13,.....
1,John,13,.....
1,John,13,.....

关于python - 用csv写两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com