提问人:Nunotrt 提问时间:11/30/2022 更新时间:11/30/2022 访问量:33
嵌套列表器中的嵌套字典如下 (Python)
nested dictionary from nested lister as follow (python)
问:
一直在为这个问题而苦苦挣扎,所以我希望我能得到一些帮助
拿了以下列表:
Buildings = ['nr1','nr2','n3']
offices = [1,3,2]
area=[23,[67,77,94],[78,79]]
price=[45,[43,89,56],[54,53]]
employees=[56,[45,54,78],[56,89]]
I would like to create following dictionary
{
{'build nr1':
{ 'office 1':
{'area' : '23 kvm',
'price' : 45
'employees' : 56}
}
}
{'build nr2':
{ 'office 1':
{'area' : '67 kvm',
'price ': 43
'employees' : 45}
}
{ 'office 2':
{'area' : '77 kvm',
'price' : 89
'employees' : 54}
}
{ 'office 3':
{'area' : '94 kvm',
'price' : 56
'employees' : 78}
}
}
{'build nr3':
{ 'office 1':
{'area' : '78 kvm',
'price' : 54
employees : 56}
}
{ 'office 2':
{'area' : '79 kvm',
'price' : 53
'employees' : 89}
}
}
}
主要目标 是创建一个数据帧,最有可能带有子列。
如“建筑物编号”作为索引,“面积”、“价格”和“雇员”作为列,以及本地 1、2、3 个子列,具体取决于索引上的建筑物是否有 3 个或更少/更多办公室......
答:
0赞
useeeeer132
11/30/2022
#1
也许这就是您要查找的代码:
import json
Buildings = ['nr1','nr2','nr3']
offices = [1,3,2]
area=[23,[67,77,94],[78,79]]
price=[45,[43,89,56],[54,53]]
employees=[56,[45,54,78],[56,89]]
myDict = dict()
for building, office in zip(Buildings, offices):
myDict[f"Build {building}"] = dict()
for i in range(office):
myDict[f"Build {building}"][f"office {i+1}"] = dict()
i = 0
for ar in area:
i += 1
j = 0
if isinstance(ar, int):
myDict[f"Build nr{i}"][f"office {j + 1}"]["area"] = f"{ar} kvm"
if isinstance(ar, list):
for element in ar:
myDict[f"Build nr{i}"][f"office {j + 1}"]["area"] = f"{element} kvm"
j += 1
k = 0
for pr in price:
k += 1
j = 0
if isinstance(pr, int):
myDict[f"Build nr{k}"][f"office {j + 1}"]["price"] = pr
if isinstance(pr, list):
for element in pr:
myDict[f"Build nr{k}"][f"office {j + 1}"]["price"] = element
j += 1
l = 0
for emp in employees:
l += 1
j = 0
if isinstance(emp, int):
myDict[f"Build nr{l}"][f"office {j + 1}"]["employees"] = emp
if isinstance(emp, list):
for element in emp:
myDict[f"Build nr{l}"][f"office {j + 1}"]["employees"] = element
j += 1
print(json.dumps(myDict, indent = 4))
其中打印:
{
"Build nr1": {
"office 1": {
"area": "23 kvm",
"price": 45,
"employees": 56
}
},
"Build nr2": {
"office 1": {
"area": "67 kvm",
"price": 43,
"employees": 45
},
"office 2": {
"area": "77 kvm",
"price": 89,
"employees": 54
},
"office 3": {
"area": "94 kvm",
"price": 56,
"employees": 78
}
},
"Build nr3": {
"office 1": {
"area": "78 kvm",
"price": 54,
"employees": 56
},
"office 2": {
"area": "79 kvm",
"price": 53,
"employees": 89
}
}
}
评论