2017-06-23 208 views
1

我有這種格式的列表:蟒蛇Django的字典

[{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
    [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}] 

我想改變它的格式:

[ 
    { 
    name:"BURGLARY", 
    data:[0, 1, 1, 0] 
    } 
    { 
    name:"PHYSICAL ASSAULT", 
    data:[0, 0, 1, 0] 
    } 
... 
] 

如何歸檔呢?請幫忙。

回答

3
data = [{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
     [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS 
     AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}] 
rlt = [{'name': key, 'data': val} for key,val in data[0].items()] 

的RLT是你想要的

+0

這傢伙去比我更快=))我t很好回答 –

2
data = [{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
    [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}] 

new_data = [{ "name": k, "data" : data[0][k]} for k in data[0]] 

輸出:

[{'data': [0, 0, 0, 1], 'name': 'ROBBERY'}, 
{'data': [2, 0, 1, 0], 'name': 'VANDALISM'}, 
{'data': [0, 0, 0, 1], 'name': 'SEXUAL HARASSMENT'}, 
{'data': [1, 3, 2, 1], 'name': 'THEFT'}, 
{'data': [0, 1, 1, 0], 'name': 'BURGLARY'}, 
{'data': [0, 0, 1, 0], 'name': 'PHYSICAL ASSAULT'}, 
{'data': [0, 0, 1, 0], 'name': 'DRUGS AND SUBSTANCE ABUSE'}] 
1
a=[{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}] 
result=[] 
for b in a: 
    for i,j in b.items(): 
     result.append({"name":i,"data":j}) 
print(result) 

輸出

[{'name': 'VANDALISM', 'data': [2, 0, 1, 0]}, {'name': 'SEXUAL HARASSMENT', 'data': [0, 0, 0, 1]}, {'name': 'PHYSICAL ASSAULT', 'data': [0, 0, 1, 0]}, {'name': 'DRUGS AND SUBSTANCE ABUSE', 'data': [0, 0, 1, 0]}, {'name': 'THEFT', 'data': [1, 3, 2, 1]}, {'name': 'ROBBERY', 'data': [0, 0, 0, 1]}, {'name': 'BURGLARY', 'data': [0, 1, 1, 0]}] 
+0

對於一個很好的老式答案,+1。但是請注意,b.items()會在內存中創建一個新列表。通過字典鍵引用會更快。 –

+0

非常感謝。 你們都很棒 –