Python 3 Tutorial for Beginners #08 – Python 3 Dictionary Basics

Python 3 dictionary is a versatile and easy to use hash-map implementation. It is simply a built-in data type that you can hack upon.

How to Create a Python 3 Dictionary

There are multiple ways you can create a dictionary. However, simplest form is using a literal.

d = {'apple': 5, 'orange': 2}

If you want to create an empty dictionary, this is how you do it:

d = {} # Creates an empty dict

When Should I use a Dictionary?

Are you looking to map a value to some other value? Then the dictionary is what you are looking for.

Note: Keys must be immutable and hashable. This means that you can use int, str, tuple, or frozenset as a key but not lists.

Python 3 Dictionary Literal Syntax

Dictionaries are made of key:value pairs. You can specify one or more pairs in the dictionary literal form. Also, commas are used to separate different key:value pairs in the dictionary.

Python 3 Dictionary Syntax Explained
Python 3 Dictionary Syntax Explained

Set and Delete Items from a Dict

Let’s take the above defined dictionary and add a new element to it. If the ‘banana’ is already present in the dictionary this will overwrite it.

d['banana'] = 4

Also, you can delete information about ‘apple’

del d['apple']

Note: You will get a KeyError exception if the given key is not present when deleting.

How to Check If a Python 3 Dictionary Has a given Key

Checking the availability of a key is very simple in Python.

if 'banana' in d:
    print('No bananas')

Also, you can check if a key is not in a dictionary

if 'apple' not in d:
    print("Oh, I deleted apples")

How to Count Number of Characters in a Phrase

Python 3 Dictionary Character Counter
Python 3 Dictionary Character Counter

That’s it for this tutorial. Next tutorial will also be about dictionaries. Please comment below if you have any questions. See Python 3 Dictionary Usage for the next awesome dictionary tutorial.

Looking for more Python Tutorials? Take a look at our Python tutorials for dabblers. We also have more Python tutorials for beginners. And while you’re here don’t forget to get the scoop on the latest tech news we’ve got just for you!


Leave a Reply
