【发布时间】:2017-12-17 20:42:31
【问题描述】:
我有一个包含大量(有意)重复的数据集。我想折叠(?)以使其更适合我的需求。数据如下所示:
Header1, Header2, Header3
Example1, Content1, Stuff1
Example1, Content2, Stuff2
Example1, Content3, Stuff3
Example2, Content1, Stuff1
Example2, Content5, Stuff5
etc...
我希望它最终成为一个字典,其中一列的值作为键,字典列表作为这些键的值,如下所示:
{Example1 : [{Header2:Content1, Header3:Stuff1}, {Header2:Content2, Header3:Stuff2}, {Header2:Content3, Header3:Stuff3}],
Example2 : [{Header2:Content1, Header3:Stuff1}, {Header2:Content5, Header3:Stuff5}]}
我是 Python 的新手,并且是一个新手程序员,所以如果这个问题令人困惑,请随时澄清。 ???谢谢!
更新 我因未发布示例代码而受到指责(感谢您让我诚实!)所以就在这里。下面的代码有效,但由于我是 Python 新手,我不知道它是否写得好。字典也以相反的顺序结束了键(Example1 和 Example2)。这并不重要,但我不明白为什么。
def gather_csv_info():
all_csv_data = []
flattened_data = {}
reading_csv = csv.DictReader(open(sys.argv[1], 'rb'))
for row in reading_csv:
all_csv_data.append(row)
for row in all_csv_data:
if row["course_sis_ids"] in flattened_data:
flattened_data[row["course_sis_ids"]].append({"user_sis_ids":row["user_sis_ids"], "file_ids":row["file_ids"]})
else:
flattened_data[row["course_sis_ids"]] = [{"user_sis_ids":row["user_sis_ids"], "file_ids":row["file_ids"]}]
return flattened_data
【问题讨论】:
-
我没有看到任何代码。您尝试了什么,为什么它不起作用?
-
你的问题太宽泛了,特别是没有任何代码来显示上下文。
-
好久没发帖了,完全忘记了自己的礼仪。感谢@MikeScotty 的那个网站,太棒了。
-
@lyonsinbeta 不客气。我已经删除了我的反对票。干杯 =)
标签: python csv dictionary