【问题标题】:If key already exists in a dict, how to add multiple values to it (Python)如果字典中已经存在键,如何向它添加多个值(Python)
【发布时间】:2021-11-06 05:57:19
【问题描述】:

我正在遍历字典中的步骤,并为每个步骤提取一个联系电话号码和一个 ID,并将这些作为键/值对放入一个新的字典中:contacts

contacts = {}

for execution_step in execution_steps["steps"]:
    main_execution_context = get_execution_context(execution_step["url"])
    contact_phone = main_execution_context["contact"]
    id = main_execution_context["id"]
    contacts[contact_phone] = id

如果存在contact_phone 的重复项,即密钥已经存在,是否可以将值对 (id) 附加到现有值上,从而创建与同一电话号码关联的 id 列表?

【问题讨论】:

  • 查看this
  • 检查this out...defaultdict(list)

标签: python dictionary key-value


【解决方案1】:

将每个值保存为list。如果密钥存在,append 到列表中。

contacts = {}

for execution_step in execution_steps["steps"]:
    main_execution_context = get_execution_context(execution_step["url"])
    contact_phone = main_execution_context["contact"]
    if contact_phone not in contacts:
        contacts[contact_phone] = list()
    contacts[contact_phone].append(main_execution_context["id"])
编辑:

添加新键:

contacts["example_number"] = list()
contacts['example_number'].append(main_execution_context["id"])

或者:

contacts["example_number"] = [main_execution_context["id"]]

【讨论】:

  • 谢谢!如何将新密钥添加到联系人字典中?目前,当我尝试添加新密钥时,在运行以下命令时,“example_number”上出现 KeyError:contacts['example_number'].append(main_execution_context["id"])
【解决方案2】:

您可以使用defaultdict。只显示关键代码:

from collections import defaultdict
contacts = defaultdict(list)
contacts[contact_phone].append(id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2017-01-04
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多