Dictionaries of unknown structure - defaultdict

Data Types in Python

Jason Myers

Instructor

Dictionary Handling

for park_id, name in nyc_eateries_parks:
    if park_id not in eateries_by_park:
       eateries_by_park[park_id] = []
    eateries_by_park[park_id].append(name)

print(eateries_by_park['M010'])
{'MOHAMMAD MATIN','PRODUCTS CORP.', 'Loeb Boathouse Restaurant',
'Nandita Inc.', 'SALIM AHAMED', 'THE NY PICNIC COMPANY', 
'THE NEW YORK PICNIC COMPANY, INC.', 'NANDITA, INC.', 
'JANANI FOOD SERVICE, INC.'}
Data Types in Python

Using defaultdict

  • Pass it a default type that every key will have even if it doesn't currently exist
  • Works exactly like a dictionary
from collections import defaultdict

eateries_by_park = defaultdict(list)
for park_id, name in nyc_eateries_parks: eateries_by_park[park_id].append(name)
print(eateries_by_park['M010'])
{'MOHAMMAD MATIN','PRODUCTS CORP.', 'Loeb Boathouse Restaurant', 
'Nandita Inc.', 'SALIM AHAMED', 'THE NY PICNIC COMPANY', 
'THE NEW YORK PICNIC COMPANY, INC.', 'NANDITA, INC.', ...}
Data Types in Python

Using defaultdict

from collections import defaultdict

eatery_contact_types = defaultdict(int)
for eatery in nyc_eateries: if eatery.get('phone'): eatery_contact_types['phones'] += 1 if eatery.get('website'): eatery_contact_types['websites'] += 1
print(eatery_contact_types)
defaultdict(<class 'int'>, {'phones': 28, 'websites': 31})
Data Types in Python

Let's practice!

Data Types in Python

Preparing Video For Download...