Python Dictionaries π«
kster
Posted on September 25, 2022
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
" "
or''
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. ( BUT don't worry 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
Try it yourself ! Open the replit and add a single key:value pair to our empty_dict
we created.
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'}
Syntax for overwriting existing values:
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'}
Posted on September 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.