python列表树索引
我有一个列表,我想在其中存储一个名字,在名字里面有更多的项目列表,有名字和金额,你可以看到下面的大致轮廓python列表树索引,python,json,python-3.x,indexing,Python,Json,Python 3.x,Indexing,我有一个列表,我想在其中存储一个名字,在名字里面有更多的项目列表,有名字和金额,你可以看到下面的大致轮廓 varx = [ {"Name1": { "itemList": { "item1":100, "item2":100, "item3":100, "item4":100, "item5":100
varx = [
{"Name1":
{
"itemList":
{
"item1":100,
"item2":100,
"item3":100,
"item4":100,
"item5":100
},
"otherStuff":
{
"stuff1":100,
"stuff2":100,
"stuff3":100,
}
},
"Name2":
{
"itemList":
{
"item1":100,
"item2":100,
"item3":100,
"item4":100,
"item5":100
},
"otherStuff":
{
"stuff1":100,
"stuff2":100,
"stuff3":100
}}}]
假设存在“name1”到“name50”,如果您只知道“name34”而不知道它的索引,我如何在“name34”的项目列表中添加项目?只需使用嵌套字典(即,松开列表部分): 印刷品:
{'item1': 100, 'item3': 100, 'item2': 100, 'item5': 100, 'item4': 100, 'item6': 100}
{'Item1': 10, 'Item6': 100}
{"Name5": {"ItemList": {"Item33": 14, "Item2": 13, "Item1": 12}},
"Name4": {"ItemList": {"Item33": 11, "Item2": 10, "Item1": 9}},
"Name3": {"ItemList": {"Item33": 8, "Item2": 7, "Item1": 6}},
"Name2": {"ItemList": {"Item33": 5, "Item2": 4, "Item1": 3}},
"Name1": {"ItemList": {"Item33": 2, "Item2": 1, "Item1": 0}}}
如果您需要中间级别,可以按照以下方式进行操作:
from collections import defaultdict
data = defaultdict(lambda: defaultdict(dict))
data['Name34']['IntemList']['Item1']=10
data['Name34']['IntemList']['Item6']=100
print(data['Name34']['IntemList'])
印刷品:
{'item1': 100, 'item3': 100, 'item2': 100, 'item5': 100, 'item4': 100, 'item6': 100}
{'Item1': 10, 'Item6': 100}
{"Name5": {"ItemList": {"Item33": 14, "Item2": 13, "Item1": 12}},
"Name4": {"ItemList": {"Item33": 11, "Item2": 10, "Item1": 9}},
"Name3": {"ItemList": {"Item33": 8, "Item2": 7, "Item1": 6}},
"Name2": {"ItemList": {"Item33": 5, "Item2": 4, "Item1": 3}},
"Name1": {"ItemList": {"Item33": 2, "Item2": 1, "Item1": 0}}}
您可以直接将其转换为json:
from collections import defaultdict
import json
data = defaultdict(lambda: defaultdict(dict))
i=0
for k1 in ['Name{}'.format(j) for j in range(1,6)]:
for k2 in ('Item1', 'Item2', 'Item33'):
data[k1]['ItemList'][k2]=i
i+=1
print(json.dumps(data))
印刷品:
{'item1': 100, 'item3': 100, 'item2': 100, 'item5': 100, 'item4': 100, 'item6': 100}
{'Item1': 10, 'Item6': 100}
{"Name5": {"ItemList": {"Item33": 14, "Item2": 13, "Item1": 12}},
"Name4": {"ItemList": {"Item33": 11, "Item2": 10, "Item1": 9}},
"Name3": {"ItemList": {"Item33": 8, "Item2": 7, "Item1": 6}},
"Name2": {"ItemList": {"Item33": 5, "Item2": 4, "Item1": 3}},
"Name1": {"ItemList": {"Item33": 2, "Item2": 1, "Item1": 0}}}
你需要它成为一个列表吗?这是一个包含1个元素的列表。看看这个。我想这就是你要找的。