Python 从csv创建dictionary对象以作为post请求发送的更有效的方法
样本数据:Python 从csv创建dictionary对象以作为post请求发送的更有效的方法,python,pandas,Python,Pandas,样本数据: data = {'account': {0: 'ted', 1: 'ned', 2: 'bed', 3: 'fred', 4: 'med'}, 'account_type': {0: 'Enterprise', 1: 'Enterprise', 2: 'Enterprise', 3: '', 4: 'Mid-Market'}, 'rep': {0: 'bob', 1: 'sam', 2: 'sam', 3: 'bob', 4: 'tim'}, 'id': {0: 5542, 1:
data = {'account': {0: 'ted',
1: 'ned',
2: 'bed',
3: 'fred',
4: 'med'},
'account_type': {0: 'Enterprise',
1: 'Enterprise',
2: 'Enterprise',
3: '',
4: 'Mid-Market'},
'rep': {0: 'bob', 1: 'sam', 2: 'sam', 3: 'bob', 4: 'tim'},
'id': {0: 5542, 1: 7118, 2: 5510, 3: 5872, 4: 5766},
'industry': {0: 'Electronics', 1: 'Retail', 2: '', 3: 'Books', 4: ''}}
df = pd.DataFrame(data=data)
我通过执行以下操作创建了所需的输出:
properties = {'app_id':'12345','users':[]}
for i in df.index:
_id = np.asscalar(np.int64(df.loc[i,'id']))
properties['users'].append(
{
'id': _id,
'properties': {
'account': df.loc[i, 'account'],
'rep': df.loc[i, 'rep'],
'account_type': df.loc[i, 'account_type'],
'industry': df.loc[i, 'industry']
}
}
)
我觉得这是难以置信的乏味,我想知道一个不需要循环的更优雅的解决方案会有什么结果 更简洁的解决方案是使用和: 使用理解:
properties = {
'app_id': '12345',
'users': [dict(
id=i[0],
properties=dict(
account=i[1],
rep=i[2],
account_type=i[3],
industry=i[4],
)
) for i in zip(df.id, df.account, df.rep, df.account_type, df.industry)]
}
这真漂亮!你能想出任何方法来压缩列表等,这样你就不必循环了吗?
properties = {
'app_id': '12345',
'users': [dict(
id=i[0],
properties=dict(
account=i[1],
rep=i[2],
account_type=i[3],
industry=i[4],
)
) for i in zip(df.id, df.account, df.rep, df.account_type, df.industry)]
}