A dictionary is an unordered set of key:value
pairs.
Dictionaries provide is a way to map pieces of data into eachother so that we can find values that are associated with one another.
Lets say we want to gather all of the calories in various candy bars 🍫
Snickers 215 🍫
Reese's 210 🍫
KitKat 218 🍫
We can create a dictionary called chocolate
to store this data:
chocolate = {'Snickers': 215, 'Reese's': 210, 'KitKat': 218}
A dictionary begins with curly brackets
{ }
Each of the keys are surrounded by quotations
" "
and eachkey:value
pairs are separated by a colon:
*** It is considered good practice to insert a space after each comma, although it will still run without the spacing.
We can also create an empty dictionary:
empty_dict = {}
A single key:value
pair can be added to the dictionary like this:
dict[key] = value
Let's try adding a single key:value pair to our empty_dict
we created before. click "➡️Run" to see the output
Multiple key:value
pairs can be added to a dictionary by using the .update()
method
empty_dict = {'a':'alpha'}
empty_dict.update({'b':'beta','g':'gamma'})
print(empty_dict)
Output:
{'a':'alpha','b':'beta','g':'gamma'}
Values can be overwritten by using this syntax:
dictonary_name['key'] = value
Let's go back to our empty_dict example and change the value of 'a' from alpha ---> apple
empty_dict = {'a':'alpha','b':'beta','g':'gamma'}
empty_dict['a'] = apple
print(empty_dict)
Output:
{'a': 'apple ', 'b': 'beta', 'g': 'gamma'}
Top comments (0)