我正在尝试将数据写入csv文件。数据格式混乱,无法更改。这就是数据字典的样子。如何将这些数据写入csv文件?
[{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}]
我尝试使用下面的代码,但是,使用此代码仅将字段名称写入csv文件中,而不写入值。
import csv
with open('peak.csv', 'w') as csvFile:
fields = ['box ', 'confidence', 'keypoints' ]
writer = csv.DictWriter(csvFile, fieldnames=fields)
writer.writeheader()
writer.writerows(result)
print("writing completed")
csvFile.close()
这是我得到的结果。 Results
答案 0 :(得分:1)
假设您要在csv中获取关键点的dict数据
import csv
results = [{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}]
with open('peak.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(result[0].keys())
for resultDict in results:
writer.writerow(resultDict.values())
csv_file.close()
CSV file content:
box, confidence, keypoints
"[277, 90, 48, 63]", 0.99, "{'left_eye': (291, 117), 'mouth_left': (296, 143), 'nose': (303, 131), 'mouth_right': (313, 141), 'right_eye': (314, 114)}"
答案 1 :(得分:0)
只需从列表中提取dic,然后使用items()编写其键和值:
with open('peak.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in list[0].items():
writer.writerow([key, value])
答案 2 :(得分:0)
这可能对您有用。虽然我不确定您要如何在“关键点”中表示键值对
import csv
myDict = [{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}]
with open('peak.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(myDict[0].keys())
for item in myDict:
writer.writerow(item.values())
print("writing completed")
csv_file.close()
输出如下:
box,confidence,keypoints
"[277, 90, 48, 63]",0.99,"{'left_eye': (291, 117), 'mouth_left': (296, 143), 'nose': (303, 131), 'mouth_right': (313, 141), 'right_eye': (314, 114)}"
答案 3 :(得分:0)
快速事物的结合。您发布的函数在fields
列表的'box'条目中有多余的空间,在python中,with
关键字将自动为您关闭文件。无需明确地执行此操作。
我已经在运行Python 3.6的计算机上对此进行了测试。我在列表中包括一个重复项,因为我假设您的数据具有多个输出列表?如果没有的话,那应该没有什么不同。
您确定以下代码无效吗?
import csv
data = [{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
},
{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}
]
# Write to csv
with open('data.csv', 'w') as f:
fields = ['box', 'confidence', 'keypoints']
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
w.writerows(data)
# Append to existing csv
with open('data.csv', 'a') as f:
fields = ['box', 'confidence', 'keypoints']
w = csv.DictWriter(f, fieldnames=fields)
w.writerows(data)
输出:
box,confidence,keypoints
"[277, 90, 48, 63]",0.99,"{'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}"
"[277, 90, 48, 63]",0.99,"{'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}"
What the output looks like in LibreCalc
如果要在它们自己的列中放置关键点的键:
import csv
data = [{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
},
{'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}
]
with open('data2.csv', 'w') as f:
# get a list of the keys in the values of 'keypoints' key
kps = data[0].get('keypoints').keys()
# make the list for the fieldnames, * just expands a list to its components
fields = ['box', 'confidence', *kps]
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
out_dict = {}
# Loop over however many data dictionaries are in the list data
for data_dict in data:
# Loop over keys and values in the dictionary
for k, v in data_dict.items():
if k != 'keypoints':
out_dict.update({k: v})
elif k == 'keypoints':
# Loop over the keys that correspond to 'keypoints' key
for k2, v2 in data_dict['keypoints'].items():
out_dict.update({k2: v2})
# Write the created out dictionary to the file
w.writerow(out_dict)
# Appending to an already existing csv
with open('data2.csv', 'a') as f:
kps = data[0].get('keypoints').keys()
# make the list for the fieldnames, * just expands a list to its components
fields = ['box', 'confidence', *kps]
w = csv.DictWriter(f, fieldnames=fields)
out_dict = {}
# Loop over however many data dictionaries are in the list data
for data_dict in data:
# Loop over keys and values in the dictionary
for k, v in data_dict.items():
if k != 'keypoints':
out_dict.update({k: v})
elif k == 'keypoints':
# Loop over the keys that correspond to 'keypoints' key
for k2, v2 in data_dict['keypoints'].items():
out_dict.update({k2: v2})
# Write the created out dictionary to the file
w.writerow(out_dict)
具有以下输出:
box,confidence,left_eye,right_eye,nose,mouth_left,mouth_right
"[277, 90, 48, 63]",0.99,"(291, 117)","(314, 114)","(303, 131)","(296, 143)","(313, 141)"
"[277, 90, 48, 63]",0.99,"(291, 117)","(314, 114)","(303, 131)","(296, 143)","(313, 141)"
第二个功能实际上与将json平展为提到的其他答案之一相同,只是没有依赖性。
答案 4 :(得分:0)
如果您不介意使用软件包,则可以从pypi安装flatten_json
软件包,用法如下:https://github.com/amirziai/flatten#usage
如果是这样,那么您的代码将变成这样:
import csv
import flatten_json
result = [
{
'box': [277, 90, 48, 63],
'confidence': 0.99,
'keypoints': {
'left_eye': (291, 117),
'right_eye': (314, 114),
'nose': (303, 131),
'mouth_left': (296, 143),
'mouth_right': (313, 141)}
}
]
flattened_result = flatten_json.flatten(result[0])
with open('peak.csv', 'w') as csvFile:
fields = list(flattened_result.keys())
writer = csv.DictWriter(csvFile, fieldnames=fields)
writer.writeheader()
writer.writerow(flattened_result)
print("writing completed")
输出如下:
box_0,box_1,box_2,box_3,confidence,keypoints_left_eye,keypoints_right_eye,keypoints_nose,keypoints_mouth_left,keypoints_mouth_right
277,90,48,63,0.99,"(291, 117)","(314, 114)","(303, 131)","(296, 143)","(313, 141)"