簡體   English   中英

在Python中更新並創建一個多維字典

[英]Update and create a multi-dimensional dictionary in Python

我正在解析存儲各種代碼片段的JSON,我首先構建這些片段使用的語言字典:

snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}}

然后當循環通過JSON我想要將關於該片段的信息添加到它自己的字典中到上面列出的字典。 例如,如果我有一個JS片段 - 最終結果將是:

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}

不要混淆水域 - 但是在PHP中使用多維數組我會做以下事情(我正在尋找類似的東西):

snippets['js'][] = array here

我知道我看到一兩個人在談論如何創建一個多維字典 - 但似乎無法追蹤在python中向字典添加字典。 謝謝您的幫助。

這稱為autovivification

你可以用defaultdict來做

def tree():
    return collections.defaultdict(tree)

d = tree()
d['js']['title'] = 'Script1'

如果想要有列表,你可以這樣做:

d = collections.defaultdict(list)
d['js'].append({'foo': 'bar'})
d['js'].append({'other': 'thing'})

default的想法是在訪問密鑰時自動創建元素。 順便說一句,對於這個簡單的案例,你可以簡單地做:

d = {}
d['js'] = [{'foo': 'bar'}, {'other': 'thing'}]

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}

在我看來,你想要一個字典列表。 這里有一些python代碼,希望能夠產生你想要的東西

snippets = {'python': [], 'text': [], 'php': [], 'js': []}
snippets['js'].append({"title":"Script 1","code":"code here", "id":"123456"})
snippets['js'].append({"title":"Script 1","code":"code here", "id":"123457"})
print(snippets['js']) #[{'code': 'code here', 'id': '123456', 'title': 'Script 1'}, {'code': 'code here', 'id': '123457', 'title': 'Script 1'}]

這清楚了嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM