Python dictionaries

Python for MATLAB Users

Justin Kiggins

Product Manager

What is a dictionary?

  • Similar to a MATLAB structure array
  • Collection of key:value pairs
  • Ordering is not guaranteed
Python for MATLAB Users

Retrieving data from a dictionary

type(definitions)
dict
print(definitions['aardvark'])
A nocturnal burrowing mammal with long ears, a tubular snout, and a long 
extensible tongue, feeding on ants and termites. Aardvarks are native to 
Africa and have no close relatives.
Python for MATLAB Users

Creating dictionaries

# Create a dictionary
dog = {'name': 'Toby', 'breed': 'Basset Hound'}
Python for MATLAB Users

Adding data to a dictionary

# Add more key:value pairs
dog['weight (lbs)'] = 552.3
dog['birthdate'] = "2016-06-26"
print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 552.3, 
 'birthdate': '2016-06-26'}
Python for MATLAB Users

Updating dictionaries

# Update weight value
dog['weight (lbs)'] = 52.3

print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 52.3,
 'birthdate': '2016-06-26'}
Python for MATLAB Users

Removing data from a dictionary

dog.pop('birthdate')
print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 52.3}
Python for MATLAB Users

Let's practice!

Python for MATLAB Users

Preparing Video For Download...