简体   繁体   English

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

[英]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.

相关问题 如何在不合并它们的情况下将多个元组(列表,等等)添加到单个字典键中? - How do you add multiple tuples(lists, whatever) to a single dictionary key without merging them? 如何在没有逗号的情况下将多个值添加到字典中的单个键中? - How can you add multiple values into a single key in a dictionary without it having commas? 在不合并元组的情况下将多个元组添加到单个字典键中? - Adding multiple tuples to a single dictionary key without merging the tuples? 如何将两个列表添加到一个新列表中而不在 Python 中合并它们? - How to add two lists into a new one without merging them in Python? 如何组合多个列表并将它们作为单个键放入字典? - How to combine several lists and put them as a single key into a dictionary? CSV至Python字典,其中一个键具有多个列表 - CSV to Python Dictionary with multiple lists for one key 如何从 CSV 制作字典键? - How do you make a dictionary key from a CSV? 如何将多个列表附加到python字典中的一个键? - How do I append multiple lists to one key in a python dictionary? 如何使用 python 将这些多个列表转换成一个大字典 - How do I convert these multiple lists into a big dictionary using python 构造一个合并多个列表的字典 - Construct a dictionary merging multiple lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM