我对python程序不熟悉,有人可以帮忙吗?非常感谢!
def ConvertInputFileJsonStr(InputCsvPath):
#### Detail Data ####
fo = open(InputCsvPath, "r")
ColumnValuesCSVColumns = (
'externalDataRef', 'language','mailingListLibraryId','surveyID')
reader = csv.DictReader(fo, ColumnValuesCSVColumns)
ls = []
for row in reader:
ls.append(row)
groups = []
uniquekeys = []
for k, g in groupby(ls, lambda r: (r['externalDataRef'],r['language'], r['surveyID'])):
groups.append({
"externalDataRef": k[0],
"language": k[1],
"surveyID": k[2],
"qualtricsDetails": [{k: v for k, v in d.items() if k not in ['externalDataRef','language','surveyID']} for d in list(g)]
})
uniquekeys.append(k)
return groups
fo.close()
它将返回
[
{
"externalDataRef": "535985",
"language": "EN",
"qualtricsDetails": [{
"mailingListLibraryId": "9011111111111"
}],
"surveyID": "123456789"
}
]
但我希望将其转换为以下示例。 我该怎么办?
[
{
"externalDataRef": "535985",
"language": "EN",
"qualtricsDetails": {
"mailingListLibraryId": "9011111111111"
},
"surveyID": "123456789"
}
]
答案 0 :(得分:0)
您需要获取列表的第一项。
您可以这样做,但是如果结果为空,则会出现list index out of range
错误。
"qualtricsDetails": [{k: v for k, v in d.items() if k not in ['externalDataRef','language','surveyID']} for d in list(g)][0]
答案 1 :(得分:0)
看起来您只有以下4列:
'externalDataRef', 'language', 'mailingListLibraryId', 'surveyID'
因此,通过更改以下行,您可以使用更简单的语法轻松实现目标:
"qualtricsDetails": [{k: v for k, v in d.items() if k not in ['externalDataRef','language','surveyID']} for d in list(g)]
})
对此:
"qualtricsDetails": {"mailingListLibraryId": k[3]}
请告诉我是否有帮助。