[英]Defining a nested dictionary in python
我想在python中定義一個嵌套字典。 我嘗試了以下方法:
keyword = 'MyTest' # Later I want to pull this iterating through a list
key = 'test1'
sections = dict(keyword={}) #This is clearly wrong but how do I get the string representation?
sections[keyword][key] = 'Some value'
我可以做這個:
sections = {}
sections[keyword] = {}
但是在Pycharm中有一個警告說它可以通過字典標簽來定義。
有人可以指出如何實現這一目標嗎?
keyword = 'MyTest' # Later I want to pull this iterating through a list
key = 'test1'
sections = {keyword: {}}
sections[keyword][key] = 'Some value'
print(sections)
{'MyTest': {'test1': 'Some value'}}
dict(keyword={})
創建一個字符串"keyword"
作為鍵而不是變量關鍵字的值。
In [3]: dict(foo={})
Out[3]: {'foo': {}}
使用dict文字實際上使用上面變量的值。
sections = {}
keyword = 'MyTest'
# If keyword isn't yet a key in the sections dict,
# add it and set the value to an empty dict
if keyword not in sections:
sections[keyword] = {}
key = 'test1'
sections[keyword][key] = 'Some value'
另外,您可以使用defaultdict ,它將在第一次訪問關鍵字時自動創建內部字典
from collections import defaultdict
sections = defaultdict(dict)
keyword = 'MyTest'
key = 'test1'
sections[keyword][key] = 'Some value'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.