簡體   English   中英

將列表的字典寫入CSV文件

[英]Write dictionary of lists to a CSV file

我正在努力將列表字典寫入.csv文件。

這是我的字典的樣子:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]

我希望.csv文件看起來像:

key1  key2  key3
1     4     7  
2     5     8
3     6     9

首先,我寫標題:

outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())

到目前為止很好...但是,我的問題是我不知道如何將一個列表分配給相應的列。 例如:

for i in range(0,len(dict[key1])):
    writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])

將隨機填充列。 另一個問題是,我必須手動填寫鍵,並且不能將其用於具有4個鍵的另一本詞典。

如果您不關心列的順序(因為字典是無序的),則可以簡單地使用zip()

d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile)
   writer.writerow(d.keys())
   writer.writerows(zip(*d.values()))

結果:

key3    key2    key1
7       4       1
8       5       2
9       6       3

如果您確實關心訂單,則需要對鍵進行排序:

keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile, delimiter = "\t")
   writer.writerow(keys)
   writer.writerows(zip(*[d[key] for key in keys]))

結果:

key1    key2    key3
1       4       7
2       5       8
3       6       9

即使鍵中的列表長度不同,這也將起作用。

    with myFile:  
        writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))   
        writer.writeheader()
        while True:
            data={}
            for key in clusterWordMap:
                try:
                    data[key] = clusterWordMap[key][ind]
                except:
                    pass
            if not data:
                break
            writer.writerow(data)

您可以使用熊貓將其保存到csv中:

df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)

給定

dict = {}
dict['key1']=[1,2,3]
dict['key2']=[4,5,6]
dict['key3']=[7,8,9]

如下代碼:

COL_WIDTH = 6
FMT = "%%-%ds" % COL_WIDTH

keys = sorted(dict.keys())

with open('out.csv', 'w') as csv:
    # Write keys    
    csv.write(''.join([FMT % k for k in keys]) + '\n')

    # Assume all values of dict are equal
    for i in range(len(dict[keys[0]])):
        csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')

產生如下的csv:

key1  key2  key3
1     4     7
2     5     8
3     6     9

在沒有csv模塊的情況下自行滾動:

d = {'key1' : [1,2,3],
     'key2' : [4,5,6],
     'key3' : [7,8,9]}

column_sequence = sorted(d.keys())
width = 6
fmt = '{{:<{}}}'.format(width)
fmt = fmt*len(column_sequence) + '\n'

output_rows = zip(*[d[key] for key in column_sequence])

with open('out.txt', 'wb') as f:
    f.write(fmt.format(*column_sequence))
    for row in output_rows:
        f.write(fmt.format(*row))
key_list = my_dict.keys()    
limit = len(my_dict[key_list[0]])    

for index in range(limit):    
  writefile.writerow([my_dict[x][index] for x in key_list])

救:

with open(path, 'a') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in dict_.items():
        writer.writerow([key, ','.join(value)])
csv_file.close()        
print ('saving is complete') 

回過頭再讀:

with open(csv_path, 'rb') as csv_file:
    reader = csv.reader(csv_file);
    temp_dict = dict(reader);
mydict={k:v.split(',') for k,v in temp_dict.items()}    
csv_file.close()
return mydict 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM