5

I want to take an empty dictionary and dynamically make it a dictionary of lists. In other words, I have an empty dictionary, and as I read in values one by one from a file, I would like to append them one by one to a given dictionary key (which may or may not exist already).

The challenge is that I can't create the list at once. I can only append values one by one, but I'm not sure how I can tell Python that I want a dictionary of lists when I add the first element.

If the dictionary starts out as empty, then how can I make it a dictionary of lists when I create the first key-value pair? How would I then go about appending subsequent values to the same key?

AlwaysQuestioning
  • 1,464
  • 4
  • 24
  • 48

1 Answers1

14

How about:

def add_element(dict, key, value):
    if key not in dict:
        dict[key] = []
    dict[key].append(value)

d = {}
add_element(d, 'foo', 'val1')
add_element(d, 'foo', 'val2')
add_element(d, 'bar', 'val3')
dkarchmer
  • 5,434
  • 4
  • 24
  • 37