首页 > 解决方案 > Python 字典:返回列表或字符串中的第一个值

问题描述

我有一个字典列表,其中我试图将键“用户名”的值作为新字典中的键,并将后续键值对作为新字典中“用户名”键的字典值.

GECOS如果值是列表,则其中一项检查涉及从列表中返回第一个元素,否则返回GECOS键的字符串值。

对于前两个字典,我无法获取整个字符串。

我有以下数据:

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 json
new_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"
        ]
    }
}

预期的输出是:

{
    "root": {
        "uid": "0",
        "Gecos": "root",
        "Group List": []
    },
    "daemon": {
        "uid": "1",
        "Gecos": "daemon",
        "Group List": []
    },
    "hplip": {
        "uid": "118",
        "Gecos": "HPLIP system user",
        "Group List": []
    },
    "speech-dispatcher": {
        "uid": "111",
        "Gecos": "Speech Dispatcher",
        "Group List": [
            "pulse",
            "test"
        ]
    }
}

标签: pythonpython-3.xlistdictionary

解决方案


您不应该遍历每个字典的键。相反,直接访问密钥,因为 dict 应该:

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))

推荐阅读