首页 > 解决方案 > 使用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"
  ]
}

我该如何解决上述问题?

标签: pythonjson

解决方案


在我看来,最好的办法是使用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']}

推荐阅读