[英]Python: defaultdict(dict) how to create nested dictionary?
我需要從目錄中的所有文件中獲取字符串並以某種方式記錄它們,因此我嘗試使用defaultdict來創建它,但是我很難確定如何逐步添加到字典的每一層。 本質上,字典應該是這樣的:
文檔名稱
束
信息
束
信息
文檔名稱
束
信息
等我將信息作為列表,因此我可以將所需的任何內容追加到列表中,但是當我運行此處的內容時,最終得到的是每個文件名的單個捆綁包和信息。 似乎update()函數正在替換內部的值,並且我不確定如何使其不斷添加,然后為每個Bundle創建更新的字典。 感謝您的幫助,對於任何混亂,我們深表歉意。
import collections
import os
devices = collections.defaultdict(lambda: collections.defaultdict(dict))
# bundles = collections.defaultdict(dict)
for filename in os.listdir('.'):
if os.path.isfile(filename):
if '.net' in filename:
dev = open(filename)
for line in dev:
line = line.strip()
values = line.split(' ')
if values[0] == 'interface':
bundle_name = values[1]
if '/' in bundle_name:
pass
else:
if len(values) == 2:
ur_device = devices[filename]
ur_device.update(
{
'bundle_name': bundle_name,
'bundle_info': [],
}
)
if 'secondary' in values:
pass
elif values[0] == 'ipv4' and values[1] == 'address' and len(values) == 4:
ur_device['bundle_info'].append(
{
'ip_address': values[2],
'subnet_mask': values[3],
}
)
dev.close()
字典是具有鍵和值的東西,每當您將東西放入具有相同鍵的字典中時,它將替換該值。 例如:
dictionary = {}
# Insert value1 at index key1
dictionary["key1"] = "value1"
# Overwrite the value at index key1 to value2
dictionary["key1"] = "value2"
print(dictionary["key1"]) # prints value2
有些事情對您的代碼沒有意義,但是我建議您使用上述語法將內容實際添加到字典中(而不是使用update方法,因為該方法用於在其中添加鍵/值對列表)一本字典)。
下面,我用#**標記了一些對您的代碼的建議
import collections
import os
#** I'm guessing you want to put your devices into this dict, but you never put anything into it
devices = collections.defaultdict(lambda: collections.defaultdict(dict))
# bundles = collections.defaultdict(dict)
for filename in os.listdir('.'):
if os.path.isfile(filename):
if '.net' in filename:
dev = open(filename)
for line in dev:
line = line.strip()
values = line.split(' ')
#** declare bundle_name out here, it is better form since we will make use of it in the immediate scopes below this
bundle_name = ''
if values[0] == 'interface':
bundle_name = values[1]
if '/' in bundle_name:
pass
else:
if len(values) == 2:
#** This is assuming you populated devices somewhere else??
devices[filename][bundle_name] = []
if 'secondary' in values:
pass
elif values[0] == 'ipv4' and values[1] == 'address' and len(values) == 4:
#** ur_device was not declared in this scope, it is a bad idea to use it here, instead index it out of the devices dict
#** it also might be worth having a check here to ensure devices[filename] actually exists first
devices[filename][bundle_name].append(
{
'ip_address': values[2],
'subnet_mask': values[3],
}
)
dev.close()
**編輯**
查看您的問題,每個文件名需要有多個捆綁軟件。 但是您的字典結構不夠詳細,您似乎也沒有提供有關如何使用數據初始化設備的代碼。
基本上,您應該考慮字典的每個級別將具有哪些鍵,而不僅僅是值。
設備(文件名:設備)
device(bundle_name ?: info)<-您缺少此詞典
信息(您將詳細信息附加到的列表)
我根據您的預期盡最大的猜測更改了上面的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.