Get startedGet started for free

Dictionaries of unknown structure - Defaultdict

1. Dictionaries of unknown structure - defaultdict

Often, we'll be working with data where we don't know all the keys that will be used, but we want to store a complex structure under those keys. A good example is I want every key to have a list of values. I'd have to initialize every key with an empty list then add the values to the list. Here is an example of just that.

2. Dictionary Handling

I start by looping over a list of tuples with the park's id and the name of the eatery. Then I check to see if I have a list for that park already in my dictionary. If not I create an empty list. Next, I append the name of the eatery to the list for that park id. Thankfully, collections provides an easier way using defaultdict.

3. Using defaultdict

Defaultdict accepts a type that every value will default to if the key is not present in the dictionary. You can override that type by setting the key manually to a value of different type. Still working with the NYC Parks eatery data, I have a list of tuples that contain the park id and the name of an eatery. I want to create a list of eateries by park. I begin by importing defaultdict from collections. Next, I create a defaultdict that defaults to a list. Next I iterate over my data and unpack it into the park_id and name. I append each eatery name into list for each park id. Finally, I print the eateries in the park with the ID is M010, which if you are curious is Central Park. Let's look at another example.

4. Using defaultdict

It's also common to use a defaultdict as a type of counter for a list of dictionaries where we are counting multiple keys from those dictionaries. In our NYC park eateries, I was curious how many had a published phone number or a website. This time when creating my defaultdict, I tell it I want it to be an int. Then I look over my nyc_eateries data and add 1 to the phones key on my defaultdict if it has a phone number that is not None. Then I add 1 to the websites key if it has a website. Finally, I print my defaultdict to see the counts.

5. Let's practice!

Let's go practice.