我有一个字符串字节
data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4' # No \n at the end
结果应该像
result = [
{"field1": "ra1", "field2": "rb1", "field3": "rc1"},
{"field1": "ra2", "field2": "rb2", "field3": "rc2"},
{"field1": "ra3", "field2": "rb3", "field3": "rc3"},
{"field1": "ra4", "field2": "rb4", "field3": "rc4"}
]
我尝试了
result = csv.DictReader(data, fieldnames=('field1', 'field2', 'field3'))
请注意,我在这里不处理任何CSV文件。
我知道我们需要将文件对象作为第一个参数传递给上述DictReader方法,以获得以上结果。
python 3.6中是否有任何类似的内置方法来实现我的结果?
在这里,我不想使用循环,因为我的数据将非常庞大。
答案 0 :(得分:0)
您可以先分割\n
,然后再分割,
然后,您可以使用每个值子列表的zip
键来创建字典列表
因此代码将是
data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4'
keys = ['field1', 'field2', 'field3']
#Create list of lists for values
values = [ item.split(',') for item in data.decode('utf-8').splitlines() ]
#[['ra1', 'rb1', 'rc1'], ['ra2', 'rb2', 'rc2'], ['ra3', 'rb3', 'rc3'], ['ra4', 'rb4', 'rc4']]
#Create result dictionary by zipping keys and values
result = [dict(zip(keys, value)) for value in values]
print(result)
输出将是
[{'field1': 'ra1', 'field2': 'rb1', 'field3': 'rc1'},
{'field1': 'ra2', 'field2': 'rb2', 'field3': 'rc2'},
{'field1': 'ra3', 'field2': 'rb3', 'field3': 'rc3'},
{'field1': 'ra4', 'field2': 'rb4', 'field3': 'rc4'}]
答案 1 :(得分:0)
import pandas as pd, io
data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4'
names = {0:'fields1',1:'fields2',2:'fields3'}
pd.read_csv(io.StringIO(data.decode('utf8')),header=None).rename(names,axis=1).to_dict('records')
[{'fields1': 'ra1', 'fields2': 'rb1', 'fields3': 'rc1'},
{'fields1': 'ra2', 'fields2': 'rb2', 'fields3': 'rc2'},
{'fields1': 'ra3', 'fields2': 'rb3', 'fields3': 'rc3'},
{'fields1': 'ra4', 'fields2': 'rb4', 'fields3': 'rc4'}]