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

后端 未结 2 1678
春和景丽
春和景丽 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 16:56

    This works:

    import csv
    
    result={}
    with open('/tmp/test.csv','r') as f:
        red=csv.DictReader(f)
        for d in red:
            result.setdefault(d['team'],[]).append(d['bldg'])
    
    #results={'1': ['1450'], '3': ['204', '250', '1437'], '2': ['1440']}
    
    0 讨论(0)
  • 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(<type 'list'>, {'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.

    0 讨论(0)
提交回复
热议问题