我有一个包含字典列表和嵌套字符串列表的字典。我找到了一种使用解析在添加项之前执行检查的方法。但是,我不确定这是否是最好、最简单的方法。
my_dict = {
'employees':[
{
'name':'Kevin',
'software':[
{
'name':'soft1',
'modules':[
'mod1',
'mod2',
'mod3'
]
},
{
'name':'soft2',
'modules':[
'mod1',
'mod2',
'mod3'
]
},
{
'name':'soft3',
'modules':[
'mod1',
'mod2',
'mod3'
]
}
]
},
{
'name':'Bob',
'software':[
{
'name':'soft3',
'modules':[
'mod4',
'mod5',
'mod6'
]
},
{
'name':'soft4',
'modules':[
'mod10'
]
},
{
'name':'soft6',
'modules':[
'mod1',
'mod5'
]
},
{
'name':'soft7',
'modules':[
'mod1',
'mod3',
'mod5'
]
}
]
}
]
}
new_employee_name = "Steward"
new_software_learnt = "soft2"
new_module_learnt = "mod20"
if not new_employee_name in [_['name'] for _ in my_dict['employees']]:
my_dict['employees'].append({'name':new_employee_name, 'software':[{"name":new_software_learnt, 'modules':[new_module_learnt]}]})
new_software_learnt = "soft3"
new_module_learnt = "mod22"
if not new_software_learnt in [_['name'] for _ in [_['software'] for _ in my_dict['employees']][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]]:
my_dict['employees'][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]['software'].append({'name':new_software_learnt, 'modules':[new_module_learnt]})
new_software_learnt = "soft3"
new_module_learnt = "mod55"
if not new_module_learnt in [_['modules'] for _ in [_['software'] for _ in my_dict['employees']][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]][[_['name'] for _ in [_['software'] for _ in my_dict['employees']][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]].index(new_software_learnt)]:
[_['modules'] for _ in [_['software'] for _ in my_dict['employees']][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]][[_['name'] for _ in [_['software'] for _ in my_dict['employees']][[_['name'] for _ in my_dict['employees']].index(new_employee_name)]].index(new_software_learnt)].append(new_module_learnt)
print(my_dict['employees'])
有没有人能建议一个更好更简化的方法?也许有一些模块在这方面很好?我是否应该更好地将解析分解为单独的函数来检查字典的每个“级别”?
最终,这个字典将被保存为json文件。
1条答案
按热度按时间x4shl7ld1#
正如您所建议的,将工作转移到一个或多个helper函数中将大大简化您的主线代码。
add_empdata()
可能应该进一步重构,但这里有一个简单而粗略的总体思想示例:输出: