如果我错了就纠正我,但是
host_dict
不是有效的字典,我假设您试图创建一个带键的字典
installed_applications
作为一个列表,它看起来像这样
host_dict = {
'installed_applications':
[{
'name': 'alsdfasdf',
'version': '1',
'installed_date': '11-11-11',
},
{
'name': 'alsdfasdf',
'version': '1',
'installed_date': '11-11-11',
},
{
'name': 'alsdfasdf',
'version': '1',
'installed_date': '11-11-11',
},
{
'name': 'alsdfasdf',
'version': '1',
'installed_date': '11-11-11',
}]
}
在这种情况下,可以通过迭代
apps
,将所需的键值对添加到列表,然后将该列表分配给
钥匙
host_dict = {}
apps = get_installed_apps(host)
host_dict['installed_applications'] = {}
#List to store list of dictionaries
li = []
#Iterate through apps
for app in apps:
#Create a dictionary for app and append to the list
dct = {}
dct['name'] = app[0]
dct['version'] = app[1]
dct['uninstall_string'] = app[2]
dct['install_date'] = app[3]
dct['install_location'] = app[4]
dct['publisher'] = app[5]
li.append(dct)
#Assign the list
host_dict['installed_applications'] = li
或者缩短代码,我们可以
host_dict = {}
apps = get_installed_apps(host)
host_dict['installed_applications'] = {}
#List to store list of dictionaries
li = []
#List of keys for app
app_keys = ['name', 'version', 'uninstall_string', 'install_date', 'install_location', 'publisher']
#Iterate through apps
for app in apps:
dct = {}
#Make the dictionary
for idx, item in enumerate(app):
dct[app_keys[item]] = item
li.append(dct)
#Assign the list
host_dict['installed_applications'] = li