python - 使用python在列表中为相同的键添加乘法值
问题描述
请检查以下代码和我的输出。我已经运行了我的代码,得到了以下输出,但我想要预期的结果。
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
预期结果是:-
{
"ABCD": "SATARA",
"XYZ": ["MUMBAI", "PUNE"]
"PQR": "43566",
"LMN": "455667"
}
我的代码:-
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
for each_split_data in list_data:
split_by_colon = each_split_data.split(":")
if split_by_colon[0] is not '':
if split_by_colon[0] in splittded_data_dict:
# append the new number to the existing array at this slot
splittded_data_dict[split_by_colon[0]].append(split_by_colon[1])
else:
# create a new array in this slot
splittded_data_dict[split_by_colon[0]] = [split_by_colon[1]]
print(json.dumps(splittded_data_dict, indent=2), "\n")
我的输出:-
{
"ABCD": [
"SATARA"
],
"REF": [
"MUMBAI.",
"PUNE"
],
"PQR": [
"43566"
],
"LMN": [
"455667"
]
}
我该如何解决上述问题?
解决方案
在我看来,最好的办法是使用defaultdict
模块collections
中的 a 。看一看:
from collections import defaultdict
list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
res = defaultdict(list)
for item in list_data:
key, value = item.split(':')
res[key].append(value)
这导致:
print(res)
# defaultdict(<class 'list'>, {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']})
或将其转换为 dict 以获得更熟悉的输出:
res = dict(res)
print(res)
# {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']}
推荐阅读
- vba - Excel VBA 如何在手动中止脚本时自动运行函数
- traversal - 遍历Array获取嵌套对象
- google-cloud-platform - 使用 gcloud cli 执行具有多个输入/输出的 Dataflow 作业
- sql - TO_CHAR (TO_DATE (1, 'j'), 'jsp') 如何将 1 作为输入,它应该将参数作为日期?
- c++ - 值模板化方法的 std::function 使用 clang 和 g++ 编译,但不使用 msvc
- ms-access - 数据导出中的访问总数不持久
- spring - Spring Session table-name 属性不改变表名
- node.js - 使用 expressJS 删除和编辑 API
- crashlytics - 多个模块的 Crashlytics 本机崩溃符号
- php - Guzzle sendAsync 返回响应