Python: Making a dictionary of lists (a hash of arrays!)

One of the standard Perl tricks is making a hash of arrays (pun intended!).

In Python this is a little trickier.

For example, you read in a file of the form: device location -- you will often need to to something like get all of the devices in New York, so you want to be able to do something like:

ny_devices = device_list["ny"]

The first thing you try is:

(device, location) = line.split(" ")
device_list[location].append(device)

This dies with: KeyError: 'ny' -- this is because the key "ny" doesn't exist yet.

One way to deal with this is:

(device, location) = line.split(" ")
if location not in device_list:
# Add empty list for location
device_list[location] = []
device_list[location].append(device)

A much cleaner way to do this is:

device_list.setdefault(location,[]).append(device)

 

Additional information