0
正在學習如何實現defaultdict,我想CID,CNAME場追加到所謂的「用戶」中「cfields」嵌套對象追加列表項目嵌套領域
嘗試下面的代碼,我有有些難度附加CID,CNAME領域
from collections import defaultdict
s = {"User":[
{"pid":1,"loc":"sf","cid":1,"cname":"Tesla"},
{"pid":1,"loc":"sf","cid":2,"cname":"Honda"},
{"pid":1,"loc":"sf","cid":3,"cname":"Jaguar"},
{"pid":2,"loc":"ch","cid":7,"cname":"Maruti"},
{"pid":2,"loc":"ch","cid":2,"cname":"Honda"},
{"pid":2,"loc":"ch","cid":9,"cname":"Jetx"}
]};
slist=s['User']
d = defaultdict(list)
for cname in slist:
key = 'cfields'
cname=slist[3] # what to write to append cid and cname to cfields ?
d[key].append(cname)
print(d)
我想有結果如下
{"User":[
{"pid":1,"loc":"sf","cfields":[{"cid":1,"cname":"Tesla"},{"cid":2,"cname":"Honda"},{"cid":3,"cname":"Jaguar"}]},
{"pid":2,"loc":"ch","cfields":[{"cid":7,"cname":"Maruti"},{"cid":2,"cname":"Honda"},{"cid":9,"cname":"Jetx"}]}
]}
你能請幫助?
非常感謝:) –