如何将多个列表添加到单个字典键而不合并它们?转换成cs

2024-05-29 03:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加多个列表到一个单一的字典键,而不合并它们,并转换为csv得到低于预期的结果

你知道吗列表.txt包含 [{A:1,B:2,C:3},{A:5,D:8,E:7,C:2}][{A:12,B:23,C:100,D:23}]

然后用固定的列标题将它们转换成csv

预期结果

A,B,C,D,E,F
1,2,3,,,
5,,2,8,7,
12,23,100,23,,

这是我的密码-

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])

给出csv中最后一个listfromtextfile[i]字典值 但在这里,我无法找到创建预期csv的逻辑。你知道吗


Tags: columnscsvcsvfile列表for字典asopen
3条回答

How do you add multiple lists to a single dictionary key without merging them?

也许有一种更优雅的方法可以做到这一点,但是有没有什么理由不能将键值建立为一个列表,然后在添加项时对其进行包装?你知道吗

a = {'key': []}

y = [4, 5, 6]
z = [1, 2, 3]

a['key'] += [y]
a['key'] += [z]

# {'key': [[4, 5, 6], [1, 2, 3]]}

参考@Tiny.D解决方案,这里是我在python2.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

假设您的source.txt中有有效内容:

[{"A":1, "B":2, "C":3},{"A":5, "D":8, "E":7, "C":2}]
[{"A":12, "B":23, "C":100, "D":23}]

-选项1:

逐行读取文件,并转换为列表,扩展为一个列表作为输出(listfromtextfile)。生成headers,其中包含listfromtextfile中的所有键(删除重复键)。生成包含所有值的row_list,作为listfromtextfile中每个元素的列表。你知道吗

之后,您可以使用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

-选项2:

使用pandas生成dict as dataframe的列表,然后调用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)

result.csv将是您想要的:

A,B,C,D,E
1,2,3,,
5,,2,8,7
12,23,100,23,

相关问题 更多 >

    热门问题