DEV Community

Cover image for Python Dictionaries 🍫
kster
kster

Posted on • Edited on

Python Dictionaries 🍫

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}
Enter fullscreen mode Exit fullscreen mode
  1. A dictionary begins with curly brackets { }

  2. Each of the keys are surrounded by quotations " " or '' and each key: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 = {}
Enter fullscreen mode Exit fullscreen mode

A single key:value pair can be added to the dictionary like this:

dict[key] = value
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'a':'alpha','b':'beta','g':'gamma'}
Enter fullscreen mode Exit fullscreen mode

diagram of key:value pairs
Syntax for overwriting existing values:

dictonary_name['key'] = value
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'a': 'apple ', 'b': 'beta', 'g': 'gamma'}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)