首页 > 解决方案 > 使用单个元素或列表作为值构建字典

问题描述

我有一个字典列表:

mydict = [
    {'name': 'test1', 'value': '1_1'},
    {'name': 'test2', 'value': '2_1'},
    {'name': 'test1', 'value': '1_2'},
    {'name': 'test1', 'value': '1_3'},
    {'name': 'test3', 'value': '3_1'},
    {'name': 'test4', 'value': '4_1'},
    {'name': 'test4', 'value': '4_2'},
]

我想用它来创建一个字典,其中的值是列表或单个值,具体取决于它们在上面列表中出现的次数。预期输出:

outputdict = {
    'test1': ['1_1', '1_2', '1_3'],
    'test2': '2_1',
    'test3': '3_1',
    'test4': ['4_1', '4_2'],
}

我尝试按照以下方式进行操作,但它总是返回一个列表,即使只有一个值元素也是如此。

outputdict = {}
outputdict.setdefault(mydict.get('name'), []).append(mydict.get('value'))

当前输出为:

outputdict = {
'test1': ['1_1', '1_2', '1_3'],
'test2': ['2_1'],
'test3': ['3_1'],
'test4': ['4_1', '4_2'],

}

标签: pythonpython-3.x

解决方案


做你已经做过的事情,然后转换单元素列表:

outputdict = {
    name: (value if len(value) > 1 else value[0])
    for name, value in outputdict.items()
}

推荐阅读