Python Dictionaries 🍫

kster

kster

Posted on September 25, 2022

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
πŸ’– πŸ’ͺ πŸ™… 🚩
kster
kster

Posted on September 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 2 of python programming 🧑
100daysofcode Day 2 of python programming 🧑

July 12, 2024

Day 1: Python Programming 🧑
100daysofcode Day 1: Python Programming 🧑

July 11, 2024

Lists in Python
python Lists in Python

October 18, 2022

Python Polymorphism
python Python Polymorphism

October 2, 2022