我在下面有一本字典
Main
或Contract
的父母。name
添加到level1词典和Contract level2词典 d = {"employee": [
{
"id": "18",
"name": "Manager",
"parent": "Main level"
},
{
"id": "19",
"name": "Employee",
"parent": "Main level"
},
{
"id": "32",
"name": "Contract",
"parent": "Contract level"
},
{
"id": "21",
"name": "Admin",
"parent": "Main level"
},
]}
预期在下面
{"employee": [
{'level1':['Manager','Employee']},
{'level2':['Test','HR']},
{
"id": "18",
"name": "Manager",
"parent": "Main level"
},
{
"id": "19",
"name": "Employee",
"parent": "Main level"
},
{
"id": "32",
"name": "Test",
"parent": "Contract level"
},
{
"id": "21",
"name": "HR",
"parent": "Contract level"
},
]}
代码
d['level1'] = {}
d['level2'] = {}
for i,j in d.items():
#check parent is Main
if j['parent'] in 'Main':
d['level1'] = j['name']
if j['parent'] in 'Contract':
d['level2'] = j['name']
我收到错误TypeError: list indices must be integers or slices, not str
答案 0 :(得分:0)
您的for
循环被误导了。
您犯了3个错误:
x in y
,以检查一个字符串是否包含另一个。尝试一下:
d["level1"] = []
d["level2"] = []
for j in d["employee"]:
# check parent is Main
if "Main" in j["parent"]:
d["level1"] += [j["name"]]
if "Contract" in j["parent"]:
d["level2"] += [j["name"]]
这将为您提供“级别”,作为员工的dict“兄弟姐妹”(而不是您真正想要的员工列表)。
要获得所需的 exact 结果,您必须执行以下操作:
level1 = []
level2 = []
for j in d["employee"]:
# check parent is Main
if "Main" in j["parent"]:
level1 += [j["name"]]
if "Contract" in j["parent"]:
level2 += [j["name"]]
d["employee"] = [{"level1": level1}, {"level2": level2}] + d["employee"]
答案 1 :(得分:0)
尝试一下:
dd = {'Main level': 'level1', 'Contract level': 'level2'}
res = {}
for x in d['employee']:
k = dd[x['parent']]
if k in res:
res[k].append(x['name'])
else:
res[k] = [x['name']]
d['employee'] = [{k: v} for k, v in res.items()] + d['employee']
print(d)
输出:
{'employee': [{'level1': ['Manager', 'Employee', 'Admin']},
{'level2': ['Contract']},
{'id': '18', 'name': 'Manager', 'parent': 'Main level'},
{'id': '19', 'name': 'Employee', 'parent': 'Main level'},
{'id': '32', 'name': 'Contract', 'parent': 'Contract level'},
{'id': '21', 'name': 'Admin', 'parent': 'Main level'}]}