ネストされたdictsを持つ列を定義する辞書を作成し、その列の値を移入するために使用することができます。カスタマイズを単一の統合された場所に保つことで、読み込み/保守が容易になり、他のcsv形式への移植が容易になります。
import copy
CSV_CONFIG = {
2: {
# Column 3 (zero-based index 2)
"name": "Shipping Details",
"Generic Field 1": "Generic Value 1",
"Generic Field 2": "Generic Value 2",
},
3: {
# Column 4 (zero-based index 3)
"name": "Personage",
"Generic Field 3": "Generic Value 3",
"Generic Field 4": "Generic Value 4",
},
}
今、あなたは異なっCSV_CONFIG
複数のネストされた列を表示するために追加"personage"
列でデータを考えると
data = []
with open(file, "r") as fh:
col_names = fh.readline().strip().split(",")
for line in fh.readlines():
line_data = {}
cols = line.strip().split(",")
for i in range(len(cols)):
if i not in CSV_CONFIG:
#this is not a nested column
line_data[col_names[i]] = cols[i]
else:
#this column is nested
nested_dict = copy.deepcopy(CSV_CONFIG[i])
nested_dict[col_names[i]] = cols[i]
del nested_dict["name"]
line_data[CSV_CONFIG[i]["name"]] = nested_dict
data.append(line_data)
に何があるかに基づいてdata
を投入、data
は今
[{
'FirstName': 'John',
'LastName': 'Doe',
'Personage': {
'Generic Field 3': 'Generic Value 3',
'Generic Field 4': 'Generic Value 4',
'Vitality': 'Alive'
},
'Shipping Details': {
'Address': '21 Pytohn Street',
'Generic Field 1': 'Generic Value 1',
'Generic Field 2': 'Generic Value 2'
}
}, {
'FirstName': 'Elvis',
'LastName': 'Presley',
'Personage': {
'Generic Field 3': 'Generic Value 3',
'Generic Field 4': 'Generic Value 4',
'Vitality': 'Deceased'
},
'Shipping Details': {
'Address': 'Elvis Presley Blvd',
'Generic Field 1': 'Generic Value 1',
'Generic Field 2': 'Generic Value 2'
}
}]
でください[あなたの質問を編集して、この出力につながる入力のサンプルを提供してください。 –
「フラット」と言うとき、行がない、つまり1つの行を意味しますか?上級者の列名を知っていますか、それともヘッダーがありますか? –
csvファイルの読み込みに問題はありませんか?そうでなければ、すべての行について:辞書を作成する(入れ子にされた値は辞書内の辞書でなければならない)。 'json.dump(Dict、outfile)'にするだけで、辞書で埋められた辞書をダンプできます。 – pwnsauce