我正在尝试处理JSON中的字典,如下所示:
{
"Parameters": {
"IP": "192.168.1.40",
"TIMEOUT": 900,
"mode": 0
},
"Device": {
"sector01": {
"nodes": ["node01", "node02"]
},
"sector02": {
"nodes": ["node01"]
},
"sector03": {
"nodes": ["node01","node02","node03"]
}
}
}
假设我没有关于存在多少个扇区和节点的信息,我想知道扇区的数量(以及每个扇区有多少个节点)。 我能够通过以下方式找到所有扇区:
len(data["Device"])
但是,在我的情况下,每个扇区的节点总数更重要。
答案 0 :(得分:1)
您可以使用for-loop
获取每个“扇区”(无论您拥有多少扇区),然后您可以在扇区中获取“节点”并检查len()
for key, val in data['Device'].items():
print(key, len(val["nodes"]))
答案 1 :(得分:0)
import json
your_json = """{
"Parameters": {
"IP": "192.168.1.40",
"TIMEOUT": 900,
"mode": 0
},
"Device": {
"sector01": {
"nodes": ["node01", "node02"]
},
"sector02": {
"nodes": ["node01"]
},
"sector03": {
"nodes": ["node01","node02","node03"]
}
}
}"""
your_dict = json.loads(your_json)
len_of_device = len(your_dict['Device'])
dict_len_of_sectors = {}
for key in your_dict['Device']:
dict_len_of_sectors[key] = len(your_dict['Device'][key]['nodes'])
print(str(dict_len_of_sectors))
我建议在这里学习更多: https://docs.python.org/3/library/stdtypes.html?highlight=dict#dict