如何将CSV文件转换为python中的词典列表

时间:2019-02-27 23:22:42

标签: python csv

我有一个csv文件,如下所示:

enter image description here

我需要将其转换为类似于以下内容的词典列表:

users = [{ "id": 0, "name": "James" },
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jake" },
{ "id": 3, "name": "Jim" },
{ "id": 4, "name": "Alex" },
{ "id": 5, "name": "Adam" },
{ "id": 6, "name": "Ryan" },
{ "id": 7, "name": "Katie" },
{ "id": 8, "name": "Julia" },
{ "id": 9, "name": "Sam" }]

我还具有一个基于每个用户ID的“连接”的CSV文件:

enter image description here

我已经尝试了好几个小时,以使其只是一个简单的元组列表,如下所示:

friends = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]

我已经尝试了导入已知的csv文件的所有方式,但是我从未尝试过要我为每个条目创建一个新词典的方法,而且我认为ive从未处理过没有这样的标头的方法。虽然我希望可以添加标题,并使我的生活更轻松,但它必须看起来像我上面给出的示例,其余的代码才能正常工作。如果您有任何想法,请告诉我。谢谢!

我完成了我的整个项目,但是不得不对提到的字典和列表进行硬编码,因为我根本不知道如何处理CSV中没有标题的标题并使它们看起来像这样。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

让我们看看如何使用标准的python WITH cte AS (SELECT t.trantype, t.cusip, t.tradedate, t.quantity, tbuy.quantity / COUNT(*) OVER(PARTITION BY t.cusip, tbuy.tradedate) new_quantity FROM temptable t LEFT JOIN temptable tbuy ON t.quantity IS NULL AND t.trantype = 'SELL' AND tbuy.trantype = 'BUY' AND tbuy.cusip = t.cusip AND tbuy.tradedate < t.tradedate AND NOT EXISTS ( SELECT 1 FROM temptable tbuy1 WHERE tbuy1.trantype = 'BUY' AND tbuy1.cusip = t.cusip AND tbuy1.tradedate < t.tradedate AND tbuy1.tradedate > tbuy.tradedate ) ) UPDATE cte SET quantity = new_quantity WHERE trantype = 'SELL' AND quantity IS NULL 模块来解析文件。

//group data n times based on passed string[] of column attributes
  group_data(elements: Observable<any>, cols: string[], index=0) : Observable<any> {
    let col = cols[index]

    let grouping = elements.pipe(
      //groupby column value
      RxOp.groupBy((el:any) => this.get_groupingValue(el, col)),

      //place key inside array
      RxOp.mergeMap((group) => group.pipe(
        RxOp.reduce((acc, cur) => [...acc, cur], ["" + group.key]))
      )
    )


    return grouping.pipe(
      RxOp.mergeMap((arr) =>
        (
        cols.length <= (index +1) ?

        //no more grouping required
        of(arr.slice(1)) : 

        //group again
        this.group_data(from(arr.slice(1)), cols, index + 1))

        // reduce result and put the key back in
        .pipe(
          RxOp.reduce((acc, cur) => [...acc, cur], ["" + arr[0]])
        )
      ),

      // map to key:group
      RxOp.map(arr => ({
          key: arr[0],
          elements: arr.slice(1)
        })
      ),
      RxOp.toArray()
    )

对于朋友来说,

csv

答案 1 :(得分:0)

据我了解,这应该可以解决您的第一个问题。您应该能够轻松地修改此代码以适合您的第二个用例。

users = []
with open('<your_file_name.csv>', 'r') as f: ##open the file in read mode
    for l in f.readlines(): ## get all the lines
        row_id, row_name = l.strip('\n').split(',')  ## unpack the values (assumes only two columns)
        users.append({'id':row_id, 'name' : row_name}) ## add to your list

如darksky所述,使用csv模块可能在代码稳定性方面更好,因此也请看一下他的答案