Lesson 12. Data Structures Part III: Dictionaries

Dictionaries are a way to store key value pairs.

In business analytics, keys are used to uniquely identify values. In databases, keys can be used to identify an entire record consisting of several values. However, we frequently just want to identify a single atomic value. For this, we can use dictionaries.

Dictionaries are created by passing in data in key value pairs separated by a colon. Each key value pair is then separated from the next key value pair by a comma. The entire set of key value pairs are surrounded by braces.

Examples

Example #1 Creating A Dictionary

In [1]:
paygrade_translation = {'O1':'2nd Lt','O2':'1st Lt','O3':'Capt'}

print(paygrade_translation)
{'O1': '2nd Lt', 'O2': '1st Lt', 'O3': 'Capt'}

Example #2 Adding A New Key Value Pair

In [4]:
paygrade_translation['O4'] = 'Maj'

print(paygrade_translation)
{'O1': '2nd Lt', 'O2': '1st Lt', 'O3': 'Capt', 'O4': 'Maj'}

Example #3 Accessing A Value In A Dictionary

In [6]:
print(paygrade_translation['O2'])
1st Lt

Copyright © 2020, Mass Street Analytics, LLC. All Rights Reserved.