我的默認字典有一個地址鍵, 并有一個與該鍵匹配的字典串列。我想將此 defaultdict 匯出到 csv 檔案。
見下文:
Right now my structure looks like this defaultdict(list)
#As you can see 1 key with multiple matching dictionaries.
#And im just copying 1 address but I have ~10 w/ varying matches
defaultdic1 =
defaultdict(list,
{'Address_1': [{'Name': 'name',
'Address_match': 'address_match_1',
'ID': 'id',
'Type': 'abc'},
{'Name': 'name',
'Address_match': 'address_match_2',
'ID': 'id',
'Type': 'abc'},
{'Name': 'name',
'Address_match': 'address_match_3',
'ID': 'id',
'Type': 'abc'}]})
我試過這樣做:
json_data = json.dumps(data_json, indent=2)
jsondf = pd.read_json(json_data, typ = 'series')
and my result was this:
Address 1 [{'Name':'name', 'Address_match':'address_match_1' 'ID' : 'id', 'Type':'abc'} {'Name':'name', 'Address_match':'address_match_2' 'ID' : 'id', 'Type':'abc'}, {'Name':'name', 'Address_match':'address_match_3' 'ID' : 'id', 'Type':'abc'}]
結果/輸出:
我想將其匯出到 excel 檔案
更新我試過這個。第一行正在列印鍵,但第二行仍在 {} 中,將它們從括號中移出并移到列中會很棒。有什么提示嗎?
for k, v in defaultdict.items():
f.writerow([k])
for values in v:
f.writerow([values])
results in CSV are:
Address 1
{'Name':'name', 'Address_match':'address_match_1' 'ID' : 'id', 'Type':'abc'}
{'Name':'name', 'Address_match':'address_match_1' 'ID' : 'id', 'Type':'abc'}
{'Name':'name', 'Address_match':'address_match_2' 'ID' : 'id', 'Type':'abc'}
我希望我的結果是:
Address 1 Name, Address_match1, ID, Type
Name, Address_match2, ID, Type
Name, Address_match3, ID, Type
Address 2 Name1, Address_match1, ID, Type
Name1, Address_match1, ID, Type
Address 3 Name1, Address_match1, ID, Type
Name1, Address_match1, ID, Type
uj5u.com熱心網友回復:
您的輸入資料和輸出資料不匹配,因此很難說出如何轉換事物,但這里有一些東西可以使用您的 defaultdict 并將其轉換為 CSV 檔案:
import csv
dic1 = {'Address_2':
[
{'Address 1':
[
{'Name':'name', 'Address_match':'address_match_1', 'ID':'id', 'Type':'abc'}
]
},
{'Address 2':
[
{'Name':'name', 'Address_match':'address_match_2', 'ID':'id', 'Type':'abc'}
]
},
{'Address 3':
[
{'Name':'name', 'Address_match':'address_match_3', 'ID':'id', 'Type':'abc'}
]
}
]
}
names = list(dic1['Address_2'][0]['Address 1'][0].keys())
myfile = csv.DictWriter( open('xxx.csv','w'), fieldnames = names )
for row in dic1['Address_2']:
myfile.writerow({'Name':list(row.keys())[0]})
myfile.writerow(list(row.values())[0][0])
uj5u.com熱心網友回復:
這就是最終解決它的原因!
names = list(dic1['Address_1'][0].keys())
f.close()
with open ("file.csv", "w", newline="") as f:
writer = csv.writer(f)
keys = names
writer.writerow(["Address"] (keys))
for k, vl in defaultdict.items():
for v in vl:
writer.writerow([k] [v[key] for key in keys])
f.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/388075.html
