鑑於從web形式接收以下數據:把一個簡單的字典到字典中嵌套列表
for key in request.form.keys():
print key, request.form.getlist(key)
group_name [u'myGroup']
category [u'social group']
creation_date [u'03/07/2013']
notes [u'Here are some notes about the group']
members[0][name] [u'Adam']
members[0][location] [u'London']
members[0][dob] [u'01/01/1981']
members[1][name] [u'Bruce']
members[1][location] [u'Cardiff']
members[1][dob] [u'02/02/1982']
我怎樣才能把它變成像這樣一本字典?它最終將用作JSON,但由於JSON和字典很容易互換,因此我的目標只是實現以下結構。
event = {
group_name : 'myGroup',
notes : 'Here are some notes about the group,
category : 'social group',
creation_date : '03/07/2013',
members : [
{
name : 'Adam',
location : 'London',
dob : '01/01/1981'
}
{
name : 'Bruce',
location : 'Cardiff',
dob : '02/02/1982'
}
]
}
這是我迄今爲止所管理的。使用下面的列表理解我可以很容易地使普通領域的意識:
event = [ (key, request.form.getlist(key)[0]) for key in request.form.keys() if key[0:7] != "catches" ]
,但我與成員列表中掙扎。可以有任意數量的成員。我想我需要爲它們單獨創建一個列表,並將其添加到包含非迭代記錄的字典中。我可以得到會員數據是這樣的:
tmp_members = [(key, request.form.getlist(key)) for key in request.form.keys() if key[0:7]=="members"]
然後我就可以拉出列表索引和字段名:
member_arr = []
members_orig = [ (key, request.form.getlist(key)[0]) for key in request.form.keys() if key[0:7] ==
"members" ]
for i in members_orig:
p1 = i[0].index('[')
p2 = i[0].index(']')
members_index = i[0][p1+1:p2]
p1 = i[0].rfind('[')
members_field = i[0][p1+1:-1]
但我怎麼添加這個到我的數據結構。以下內容不起作用,因爲我可能試圖在members[0][name]
之前處理members[1][name]
。
members_arr[int(members_index)] = {members_field : i[1]}
這似乎很複雜。有沒有一個簡單的方法來做到這一點,如果不是,我怎麼能得到這個工作?
['進口json'](https://docs.python.org/2/library/json.html) – NightShadeQueen