我有一个字典列表,其中我试图使键“Username”的值成为新字典中的键,并将随后的键值对作为新字典中的“用户名”键的字典值。其中一项检查涉及从列表中返回第一个元素(如果该值为列表),否则返回键的字符串值。GECOSGECOS对于前两个字典,我无法获取整个字符串。我有以下数据:test_list = [ { "Username": "root", "UID": "0", "GECOS": "root", "Group List": [ "" ] }, { "Username": "daemon", "UID": "1", "GECOS": "daemon", "Group List": [ "" ] }, { "Username": "hplip", "UID": "118", "GECOS": [ "HPLIP system user", "", "", "" ], "Group List": [ "" ] }, { "Username": "speech-dispatcher", "UID": "111", "GECOS": [ "Speech Dispatcher", "", "", "" ], "Group List": [ "pulse", "test" ] } ]和以下代码:import jsonnew_dict = {}for dict_item in test_list: for key in dict_item: new_dict[dict_item["Username"]] = { 'UID'.title().lower(): dict_item['UID'], 'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item[key], list) else dict_item['GECOS'], 'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List'] }print(json.dumps(new_dict, indent=4))其输出为:{ "root": { "uid": "0", "Gecos": "r", "Group List": [] }, "daemon": { "uid": "1", "Gecos": "d", "Group List": [] }, "hplip": { "uid": "118", "Gecos": "HPLIP system user", "Group List": [] }, "speech-dispatcher": { "uid": "111", "Gecos": "Speech Dispatcher", "Group List": [ "pulse", "test" ] }}
1 回答
MMMHUHU
TA贡献1834条经验 获得超8个赞
不应循环访问每个字典的键。相反,直接访问密钥,就像字典应该:
import json
new_dict = {}
for dict_item in test_list:
new_dict[dict_item["Username"]] = {
'UID'.title().lower(): dict_item['UID'],
'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item['GECOS'], list) else dict_item['GECOS'],
'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List']
}
print(json.dumps(new_dict, indent=4))
添加回答
举报
0/150
提交
取消