0

I'm looping through steps in a dictionary and pulling out a contact phone number and an id for each step, and put these as key/value pairs into a new dict: 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

Where there are duplicates of contact_phone i.e. the key already exists, is it possible to append the value pair (id) onto the existing value, thus creating a list of id's associated with the same phone number?

S.B
  • 13,077
  • 10
  • 22
  • 49
price88
  • 37
  • 10
  • Check out [this](https://stackoverflow.com/questions/20585920/how-to-add-multiple-values-to-a-dictionary-key-in-python) – 0x263A Sep 09 '21 at 14:54
  • Check [this](https://docs.python.org/3/library/collections.html#defaultdict-examples) out... `defaultdict(list)` – Suyog Shimpi Sep 09 '21 at 15:48

2 Answers2

0

Save every value as a list. If the key exists, append to the list.

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"])
Edit:

To add new keys:

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

Or:

contacts["example_number"] = [main_execution_context["id"]]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • Thank you! How am I able to add new keys into the contacts dict? At the moment when I try to add a new key I am getting a KeyError on 'example_number' when running the following: contacts['example_number'].append(main_execution_context["id"]) – price88 Sep 09 '21 at 15:22
0

You can use the defaultdict. Only key codes are shown:

from collections import defaultdict
contacts = defaultdict(list)
contacts[contact_phone].append(id)
chenzhongpu
  • 6,193
  • 8
  • 41
  • 79