2014-03-13 152 views
0

我試圖做一個字典是這樣的:Python的字典追加

d = { 'id' : counter, 'file': [ {'name': filename, 'uri' : 'http://localhost:8000/uploads/' + filename, 'path' : os.path.join(dirname, filename) } ] } 

因此,大家可以看到,我試圖做一個字典,一個ID和一個文件。 在文件中,我想'保存'文件本身的信息,如名稱,URI,路徑等......我現在遇到的問題是,我從這本字典中得到的值是最後一個。 所以我猜測我需要使用某種附件。但我不知道如何做到這一點?

感謝您的閱讀和幫助!

親切的問候,格倫

+0

你可以把一個文件的每'id'映射到這個'D'字典 – Jae

回答

3

使詞典

列表
# Create an empty list at the beginning 
list_of_dicts = [] 

# Then, for each dict you create... 
d = { 'id' : counter, 
     'file': [ {'name': filename, 
       'uri' : 'http://localhost:8000/uploads/' + filename, 
       'path' : os.path.join(dirname, filename) } ] } 
# ... add it to your list 
list_of_dicts.append(d) 

UPDATE:

我錯過了你有你的字典中的列表。如果要追加到列表,而不是,那麼就由'file'鍵從字典獲取列表:

# The dict, with the first file 
d = { 'id' : counter, 
     'file': [ {'name': filename, 
       'uri' : 'http://localhost:8000/uploads/' + filename, 
       'path' : os.path.join(dirname, filename) } ] } 

# Then append all files you want to the list found in d['file'] 
d['file'].append({'name': some_other_filename, 
        'uri': some_other_uri, 
        'path': some_other_path}) 
+0

的字典哦,我的,不認爲這是這麼簡單...我現在有點覺得愚蠢......非常感謝您的快速和正確的答案! 我正在使用for循環來填充一個更大的詞典,它使用一個ID來分隔不同的文件。 –

+0

不客氣:-) –