Read two column CSV as dict with 1st column as key

后端 未结 2 1690
春和景丽
春和景丽 2020-12-21 16:44

I have a CSV with two columns, column one is the team dedicated to a particular building in our project.

The second column is the actual building number.

Wha

2条回答
  •  忘掉有多难
    2020-12-21 17:09

    The useful collections.defaultdict in the standard library makes short work of this task:

    import csv
    import collections as co
    
    dd = co.defaultdict(list)
    with open('/path/to/your.csv'),'rb') as fin:
        dr = csv.DictReader(fin)
        for line in dr:
            dd[line['team']].append(line['bldg'])
    
    # defaultdict(, {'1': ['1450'], '3': ['204', '250', '1437'], '2': ['1440']})
    

    http://docs.python.org/2/library/collections.html#collections.defaultdict

    The first argument provides the initial value for the default_factory attribute; it defaults to None.

提交回复
热议问题