2016-05-20 39 views
-2

我有一個Python詞典的字典,並有日期存儲,我需要寫入CSV文件。我如何寫入CSV文件從字典的字典的字典,而有些值爲空

我遇到的問題是,我讀過的文件中的某些字典中沒有包含該特定ID的任何信息。所以我的CSV文件列沒有正確排列。

例如

d["first1"]["title"] = founder 
    d["first1"]["started"] = 2005 
    d["second1"]["title"] = CEO 
    d["second1"]["favcolour"] = blue 

,所以當我使用下面的代碼:

for key, value in d.iteritems(): 
ln = [key] 
     for ikey, ivalue in value.iteritems(): 
      ln.append(ikey) 
      ln.extend([v for v in ivalue]) 
     writer.writerow(ln) 

我的CSV文件,將所有的信息,但在「開始」和「favcolour」是在同一列我想要它,以便列只包含一個。

感謝所有提前

+0

可以顯示當前和預期的輸出格式嗎? –

回答

0

可以使用DictWritercsv輕鬆追加會是什麼稀疏字典到CSV。唯一需要注意的是你需要在開始時瞭解所有可能的領域。

import csv 

data = { "first": {}, "second": {} } 
data["first"]["title"] = "founder" 
data["first"]["started"] = 2005 
data["second"]["title"] = "CEO" 
data["second"]["favcolour"] = "blue" 


fieldNames = set() 

for d in data: 
    for key in data[d].keys(): 
    # Add all possible keys to fieldNames, beacuse fieldNames is 
    # a set, you can't have duplicate values 
    fieldNames.add(key) 


with open('csvFile.csv', 'w') as csvfile: 
    # Initialize DictWriter with the list of fieldNames 
    # You can sort fieldNames to whatever order you wish the CSV 
    # headers to be in. 
    writer = csv.DictWriter(csvfile, fieldnames=list(fieldNames)) 

    # Add Header to the CSV file 
    writer.writeheader() 

    # Iterate through all sub-dictionaries 
    for d in data: 
    # Add the sub-dictionary to the csv file 
    writer.writerow(data[d]) 
1

這裏有一個建議:

d = {"first1": {"title": 'founder', "started": 2005}, "second1": {"title": 'CEO', "favcolour": 'blue'}} 

columns = [] 
output = [] 
for key, value in d.iteritems(): 
    for ikey, ivalue in value.iteritems(): 
     if ikey not in columns: 
      columns.append(ikey) 
    ln = [] 
    for col in columns: 
     if col not in value: 
      ln.append('') 
     else: 
      ln.append(value[col]) 

    output.append(ln) 

with open('file', 'w') as fl: 
    csv_writer = csv.writer(fl) 
    csv_writer.writerow(columns) 
    for ln in output: 
     print ln 
     csv_writer.writerow(ln) 

文件:

started,title,favcolour 
2005,founder 
,CEO,blue 
+0

謝謝盧卡斯這工作完美 – agarc

1

如果它並不需要是人類可讀的,則可以選擇pickle使用:

import pickle 

# Write: 
with open('filename.pickle', 'wb') as handle: 
    pickle.dump(d, handle) 

# Read: 
with open('filename.pickle', 'rb') as handle: 
    d = pickle.load(handle) 
0

熊貓的作品非常適合像這樣的事情,所以如果這是一個選擇,我會推薦它。

import pandas as pd 

#not necessary, but for me it's usually easier to work with a list of dicts than dicts 
my_list = [my_dict[key] for key in my_dict] 
# When you pass a list of dictionaries to pandas DataFrame class, it will take care of 
#alignment issues for you, but if you're wanting to do something specific 
#with None values, you will need to further manipulate the frame 
df = pd.DataFrame(my_list) 
df.to_csv('file_path_to_save_to')