[英]How do you add multiple lists to a single dictionary key without merging them? and convert to csv
I am trying to add multiple lists to a single dictionary key without merging them and convert to csv to get below expected result 我正在尝试将多个列表添加到单个字典键而不合并它们并转换为csv以得到低于预期的结果
list.txt contains [{A:1, B:2, C:3},{A:5, D:8, E:7, C:2}] [{A:12, B:23, C:100, D:23}] list.txt包含[{A:1,B:2,C:3},{A:5,D:8,E:7,C:2}]] [{A:12,B:23,C:100 ,D:23}]
then covert them into csv with fixed column header which should look like 然后用固定的列标题将它们隐藏到csv中,看起来应该像
Expected Result 预期结果
A,B,C,D,E,F
1,2,3,,,
5,,2,8,7,
12,23,100,23,,
Here is my code - 这是我的代码-
csv_columns=A,B,C,D,E,F
listfromtextfile = eval(open("list").read())
def DictToCSV(csv_file,csv_columns,listIndex):
try:
with open(csv_file, 'ab') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
HeadWrite = csv.writer(csvfile)
HeadWrite.writerow(csv_columns)
for data in listIndex:
writer.writerow(data)
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
return
for i in range(len(listfromtextfile)):
DictToCSV(csv_file,csv_columns,listfromtextfile[i])
Giving last listfromtextfile[i] dictionary values in csv But here I am not able to find logic to create expected csv. 在csv中提供最后一个listfromtextfile [i]字典值,但是在这里我无法找到创建预期csv的逻辑。
How do you add multiple lists to a single dictionary key without merging them? 如何将多个列表添加到单个字典键而不合并它们?
There may be a more elegant way to do it, but is there any reason you can't establish the key value as a list and then wrap the items as you add them? 也许有一种更优雅的方法,但是有什么理由不能将键值建立为列表,然后在添加项目时将它们包装起来?
a = {'key': []}
y = [4, 5, 6]
z = [1, 2, 3]
a['key'] += [y]
a['key'] += [z]
# {'key': [[4, 5, 6], [1, 2, 3]]}
Suppose you have valid content in your source.txt
: 假设您的source.txt
包含有效内容:
[{"A":1, "B":2, "C":3},{"A":5, "D":8, "E":7, "C":2}]
[{"A":12, "B":23, "C":100, "D":23}]
- Option 1: - 选项1:
Read the file line by line, and convert to list, extend to one single list as output ( listfromtextfile
). 逐行读取文件,然后转换为列表,并扩展到一个列表作为输出( listfromtextfile
)。 Generate the headers
which contain all the keys (remove duplicate one) from listfromtextfile
. 生成headers
包含所有的按键(删除重复的一个) listfromtextfile
。 Generate the row_list
which contain all the values as a list for per element in the listfromtextfile
. 生成包含所有值的row_list
作为listfromtextfile
每个元素的listfromtextfile
。
After that, you can use csv
module to write the header row and values rows into your result.csv
: 之后,您可以使用csv
模块将标头行和值行写入result.csv
:
import csv
listfromtextfile =[]
for i in open("source.txt").readlines():
listfromtextfile.extend(eval(i)) #generate the lsit from source file
headers = set([key for e in listfromtextfile for key in e.keys()]) #generate the headers for keys
row_list = [[e.get(header,'') for header in sorted(headers)] for e in listfromtextfile ] #generate the row_list for values
with open('result.csv', 'wb') as f: # Just use 'w' mode in 3.x
wr = csv.writer(f)
wr.writerow(sorted(list(headers))) #write the header row
wr.writerows(row_list) #write values rows
- Option 2: -选项2:
Use pandas
to generate the list of dict as dataframe, then call to_csv
to write into result.csv
: 使用pandas
将dict列表生成为数据帧,然后调用to_csv
写入result.csv
:
import pandas as pd
listfromtextfile =[]
for i in open("source.txt").readlines():
listfromtextfile.extend(eval(i)) #generate the lsit from source file
df = pd.DataFrame(listfromtextfile)
df.to_csv('result.csv',index=False)
The result.csv
will be the one you want: result.csv
将是您想要的:
A,B,C,D,E
1,2,3,,
5,,2,8,7
12,23,100,23,
Taking reference from @Tiny.D solution, here is what I got working code in my python 2.6.x 从@ Tiny.D解决方案中获取参考,这是我在python 2.6.x中获得的工作代码
import csv
listfromtextfile =[]
for i in open("source.txt").readlines():
listfromtextfile.extend(eval(i)) #generate the lsit from source file
headers = set([key for e in listfromtextfile for key in e[0].keys()]) #generate the headers for keys
row_list = []
for e in listfromtextfile:
for i in range(len(e)):
row_list.append([e[i].get(header,'') for header in sorted(headers)]) #generate the row_list for values
with open('result.csv', 'wb') as f: # Just use 'w' mode in 3.x
wr = csv.writer(f)
wr.writerow(sorted(list(headers))) #write the header row
wr.writerows(row_list) #write values rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.