2016-05-05 153 views
2

我想創建一個值爲列表的字典。例如:Python創建列表的字典

"data": { 
    "1": { 
    "id": 1, 
    "name": test1, 
    "description":yyyyy 
}, 
     "2": { 
    "id": 2, 
    "name": test2, 
    "description":xxxxx 
} 
} 

當我這樣做,它只是在列表中創建 - [],但我想在列表中字典中的所有值 - } {:

data = [] 
for x in Test.objects.filter(act=True): 
    data.append({"%s" % x.id:{"id":"%s" % x.id, "name": "%s" % x.name, "description": "%s" % x.description}) 
ins = {} 
ins['instance'] = data 

結果:

"data": [ 
{ 
    "1": { 
    "id": 1, 
    "name": test1, 
    "description":yyyyy 
} 
}, 
{ 
    "2": { 
    "id": 2, 
    "name": test2, 
    "description":xxxxx 
} 
} 
] 

需要幫助。

+0

由於這些值不是列表,因此您的示例並不正確。 – tknickman

+0

列表在哪裏? –

+0

好的。我在這是新的...我想我必須通過列表。你能幫我看看例子中顯示的結果嗎? – ash

回答

1

首先,你不顯示任何列出你的問題。你想要的例子中有什麼是一個字典,其值也是一個字典。括號[]表示列表。大括號{}表示字典。列表是一個有序的項目數組。字典將值存儲在key:value對中。其次,使用按鍵序列編號的字典制作字典實在沒有意義。您可以簡單地擁有一個字典列表,並通過列表索引引用每個項目。

你也應該爲你的變量命名,而不僅僅是xtest1yyyyy

,從而爲你的問題,這聽起來像你有一些價值觀像[1,test1,yyyyy]或者說[x.id,x.name,x.description]每個項目,以對應於:idnamedescription我相信要排序此數據的方式是這樣的:

data=[ 
    {"id":1,"name":test1,"description":yyyyy}, 
    {"id":2,"name":test2,"description":xxxxx} 
] 

所以,你的代碼可能看起來像

data=[] 
for x in Test.objects.filter(act=True): 
    data.append({"id":x.id,"name":x.name,"description":x.description}) 

#Or as a list comprehension: 
#data=[{"id":x.id,"name":x.name,"description":x.description} for x in Test.objects.filter(act=True)] 

然後你就可以訪問諸如這樣

數據
for item in data: 
    print("""\ 
ITEM ID: {} 
ITEM NAME: {} 
ITEM DESCRIPTION: {} 
---------------------""".format(item["id"],item["name"],item["description"])) 

如果你真的想你在帖子中這樣描述準確格式化數據:

the_dict={} 
for index, x in enumerate(Test.objects.filter(act=True)): #assuming this is a list of objects 
    the_dict[str(index+1)]={"id":x.id,"name":x.name,"description":x.description} 
    #the +1 to start keys at 1 as in your example, instead of 0 

編輯:其實,重新閱讀你的例子後,這聽起來像你想的ID來在詞典中的關鍵,不只是從1-n個編號的任意...

在這種情況下,只要你確定有沒有重複的ID(字典鍵必須是唯一的):

the_dict={} 
for x in Test.objects.filter(act=True): 
    the_dict[str(x.id)]={"id":x.id,"name":x.name,"description":x.description} 
+0

謝謝你,鱷魚,我試過,它的工作。 – ash

1

在你的例子中,沒有列表。有一本嵌套字典的字典。試試...

data = {} 
for x in Test.objects.filter(act=True): 
    data["%s" % x.id] = {"id":"%s" % x.id, "name": "%s" % x.name, "description": "%s" % x.description} 

ins = {} 
ins['instance'] = data 

data = {} 
for x in Test.objects.filter(act=True): 
    data[str(x.id)] = {"id":str(x.id), "name": str(x.name), "description": str(x.description)} 

ins = {} 
ins['instance'] = data