如何将 csv 读取为具有多个值的字典?
How to read csv to dictionary with multiple values?
我想把下面的数据读成这样:
{
'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
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 一起使用。如果没有,请告诉我。
我想把下面的数据读成这样:
{
'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 |
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 一起使用。如果没有,请告诉我。