python数据字典排序_当标题处于混合顺序时,如何将数据存储在Python中的数据字典中...

本文介绍了一种从文本中解析数据并将其转换为CSV格式的方法。通过定义数据结构,可以轻松地处理和导出复杂的数据集。示例展示了如何读取包含学校ID和其他属性的文本行,并将其组织成易于使用的字典结构。

这看起来很简单.将文件处理为数据结构,然后将其导出到csv中.

school = None

headers = None

data = {}

for line in text.splitlines():

if line.startswith("school id"):

school = line.split('=')[1].strip()

headers = None

continue

if school is not None and headers is None:

headers = line.split('|')

continue

if school is not None and headers is not None and line:

if not school in data:

data[school] = []

datum = dict(zip(headers, line.split('|')))

data[school].append(datum)

In [29]: data

Out[29]:

{'273533123': [{'age': '27',

'degree': 'MBA',

'name': 'John B. Black',

'race': 'hispanic',

'year': '2003'},

{'age': '28',

'degree': 'PhD',

'name': 'Steven Smith',

'race': 'black',

'year': '2005'},

{'age': '25',

'degree': 'MBA',

'name': 'Jacob Waters',

'race': 'hispanic',

'year': '2003'}],

'28392': [{'age': '27',

'degree': 'PhD',

'name': 'Susan A. Smith',

'race': 'white',

'year': '2007'},

{'age': '26',

'degree': 'PhD',

'name': 'Fred Collins',

'race': 'hispanic',

'year': '2006'},

{'age': '28',

'degree': 'MBA',

'name': 'Amber Real',

'race': 'white',

'year': '2007'},

{'age': '27',

'degree': 'PhD',

'name': 'Mike Lee',

'race': 'white',

'year': '2003'}],

'3452332': [{'age': '27',

'degree': 'Bachelors',

'name': 'Peter Hintze',

'race': 'white',

'year': '2002'},

{'age': '25',

'degree': 'MBA',

'name': 'Ann Graden',

'race': 'black',

'year': '2004'},

{'age': '28',

'degree': 'PhD',

'name': 'Bryan Stewart',

'race': 'white',

'year': '2004'}]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值