Python 阅读csv到dict的dict列表
我有一个大量(有意)重复的数据集。我想把它折叠起来,使它更适合我的需要。数据如下所示:Python 阅读csv到dict的dict列表,python,csv,dictionary,Python,Csv,Dictionary,我有一个大量(有意)重复的数据集。我想把它折叠起来,使它更适合我的需要。数据如下所示: Header1, Header2, Header3 Example1, Content1, Stuff1 Example1, Content2, Stuff2 Example1, Content3, Stuff3 Example2, Content1, Stuff1 Example2, Content5, Stuff5 etc... 我希望它最终成为一个dict,第一列的值作为键,dict列表作为这些键的
Header1, Header2, Header3
Example1, Content1, Stuff1
Example1, Content2, Stuff2
Example1, Content3, Stuff3
Example2, Content1, Stuff1
Example2, Content5, Stuff5
etc...
我希望它最终成为一个dict,第一列的值作为键,dict列表作为这些键的值,如下所示:
{Example1 : [{Header2:Content1, Header3:Stuff1}, {Header2:Content2, Header3:Stuff2}, {Header2:Content3, Header3:Stuff3}],
Example2 : [{Header2:Content1, Header3:Stuff1}, {Header2:Content5, Header3:Stuff5}]}
我对Python是一个全新的新手,所以如果这个问题让人困惑,请随时澄清 我完全改变了答案,因为你改变了你的问题,所以我只是在你自己的答案中整理了代码,所以它更“Pythonic”:
不确定您为什么希望数据采用这种格式,但这取决于您。此代码可以工作,但我不知道它有多像pythonic,我也不理解为什么
flatten_data
dict的键顺序与原始CSV中的键顺序相反。严格来说,它们不整齐并不重要,但这很奇怪
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不客气。我已经取消了我的反对票。Cheers=)字典不按顺序保存键,这不是字典的用途。如果您需要顺序,请使用列表或OrderedDict。我不需要按顺序排列,我知道键:值对的意义在于它们不需要按已知顺序排列,我只是说,我不知道它们为什么按顺序排列,因为这不是它们读入dict的顺序。没有注释的向下投票没有帮助,由于人们仍在学习,因此必须猜测它为什么不好,并且可能会弄错。该文件是CSV文件,为了可读性,我只是制作了一个简单的表格。我用逗号更新了它,但留下了空格以保持可读性。不是很有帮助。如果你发布一个问题,人们会花时间试图根据你发布的内容为你提供解决方案。如果你将问题编辑成完全不同的,这些答案会被不公平地否决。你也接受了你自己的答案,这远远不是典型的代码,这对下一个程序员也不是很有帮助……如果有人提供了更好的答案,或者如果我提出了更好的答案,我会很高兴地更改选择的答案,但我提供的答案确实解决了这个问题。至少,如果有人发现了这个问题,他们会看到一个有效的解决方案,注意这是新手的尝试。我编辑了我的问题,以显示代码的改进版本。如果你愿意,你甚至可以把它复制到你的问题中。
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