2015-11-22 191 views
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"}]} 
]} 

你能請幫助?

回答

2

不知道你爲什麼想在這裏使用defaultdicts。你應該使用itertools.groupby

>>> data = [] 
>>> for g, items in itertools.groupby(s['User'], lambda x: (x['pid'], x['loc'])): 
     items = [{k: v for k, v in item.items() if k not in ('pid', 'loc')} for item in items] 
     data.append({ 'pid': g[0], 'loc': g[1], 'cfields': items }) 


>>> data 
[{'pid': 1, 'cfields': [{'cid': 1, 'cname': 'Tesla'}, {'cid': 2, 'cname': 'Honda'}, {'cid': 3, 'cname': 'Jaguar'}], 'loc': 'sf'}, {'pid': 2, 'cfields': [{'cid': 7, 'cname': 'Maruti'}, {'cid': 2, 'cname': 'Honda'}, {'cid': 9, 'cname': 'Jetx'}], 'loc': 'ch'}] 
>>> pprint.pprint(data) 
[{'cfields': [{'cid': 1, 'cname': 'Tesla'}, 
       {'cid': 2, 'cname': 'Honda'}, 
       {'cid': 3, 'cname': 'Jaguar'}], 
    'loc': 'sf', 
    'pid': 1}, 
{'cfields': [{'cid': 7, 'cname': 'Maruti'}, 
       {'cid': 2, 'cname': 'Honda'}, 
       {'cid': 9, 'cname': 'Jetx'}], 
    'loc': 'ch', 
    'pid': 2}] 
+0

非常感謝:) –