【问题标题】:How to read csv to dictionary with multiple values?如何将csv读取到具有多个值的字典?
【发布时间】:2022-01-05 16:06:02
【问题描述】:

我想像下面这样读取数据:

{
  'a' : ['row1,'row2','row3'], 
  'b' : ['row1,'row2','row3']
}
columns A columns B
a row1
a row2
a row3
b row 1
b row 2
b row 3

【问题讨论】:

    标签: python-2.7 dictionary


    【解决方案1】:
    with open(FILE) as file:
        contents = [row for row in csv.DictReader(file, delimiter=';')]
    data = {
        'a': [row['columns B'] for row in contents if row['columns A'] == 'a'],
        'b': [row['columns B'] for row in contents if row['columns A'] == 'b']}
    
    data
    # >> {'a': ['row1', 'row2', 'row3'], 'b': ['row 1', 'row 2', 'row 3']}
    

    用 Python3 测试过,但也应该适用于 Python2。如果没有,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2014-04-06
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多