python - 使用单个元素或列表作为值构建字典
问题描述
我有一个字典列表:
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'],
}
解决方案
做你已经做过的事情,然后转换单元素列表:
outputdict = {
name: (value if len(value) > 1 else value[0])
for name, value in outputdict.items()
}
推荐阅读
- wso2 - 如何从以前的版本中获取 WSO2 docker-compose 发行版
- woocommerce - Woocommerce WP allimport
- python - 使用 pymongo 教程示例复制 mongo db 失败:“OperationFailure: no such command: 'copydb'”
- python-3.x - Python 3:带有 CRS 坐标的 Geopandas 数据框到 Graph 中以查找连接的组件和其他图形属性?
- javascript - 如何合并两个数组并使它们成为 JavaScript 中的对象数组
- html - 如何在 CSS 中结合背景图像 + 线性渐变?背景图像上的线性渐变
- rubygems - jruby 总是显示,甚至已经安装了一个 gem,但它不是
- html - 页脚上的样式和位置 3 列
- linux - 有没有办法完全删除一条线?
- laravel - 如何同步()方法附加数据透视表 Laravel