Blog Posts

Python Dictionary Guide: 10 Python Dictionary Methods & Examples

Blog: Think Data Analytics Blog

Master Python Dictionaries and their essential functions in 15 minutes with this introductory guide.

This Python Dictionary tutorial covers:

With that, let’s get started.

Define a Python Dictionary

Dictionaries are written within curly brackets {}.FigureDefine a dictionary. Keys are in red. Values are in blue.

# Define a dictionary code 
webstersDict = {'person': 'a human being',
                'marathon': 'a running race that is about 26 miles',
                'resist': 'to remain strong against the force',
                'run': 'to move with haste; act quickly'}

The dictionary webstersDict used strings as keys in the dictionary, but dictionary keys can be any immutable data type (numbers, strings, tuples etc). Dictionary values can be just about anything (int, lists, functions, strings, etc).

For example, the dictionary below, genderDict has ints as keys and strings as values.

# Define a dictionary
genderDict = {0: 'male',
              1: 'female'}

An important point to emphasize is that if you try to make a key a mutable datatype (like a list), you will get an error.

# Failure to define a dictionary
webstersDict = {(1, 2.0): 'tuples can be keys',
                1: 'ints can be keys',
                'run': 'strings can be keys', 
                ['sock', 1, 2.0]: 'lists can NOT be keys'}

FigureFailure to define a dictionary with a list as a key. Lists are NOT immutable

Access Values in a Python Dictionary

To access a dictionary value, you can use square brackets [].

For example, the code below uses the key ‘marathon’ to access the value ‘a running race that is about 26 miles’.

# Get value of the 'marathon' key
webstersDict['marathon']

FigureAccess the key ‘marathon’

Keep in mind that you will get a KeyError if you try to access a value for a key that does not exist.

# Try to get value for key that does not exist
webstersDict['nonexistentKey']

FigureKeyError will result if you try and look up a key that does not exist.

In the Python Dictionary Methods section, you will see the utility of using the dictionary method get to avoid KeyErrors.

Add, Update, and Delete Keys from a Python Dictionary

Add or Update Key

You can add a new key-value pair.

# add one new key value pair to a dictionary
webstersDict['shoe'] = 'an external covering for the human foot'

FigureAdd the new key ‘shoe’ to the dictionary. The new key ‘shoe’ is enclosed in the red rectangle.

You can also update a key-value pair.FigureUpdate the dictionary key ‘marathon’

In the Python Dictionary Methods section, you will see that you can also add or update multiple key value pairs at a time using the dictionary update method.

Delete Keys from Python Dictionary

It is possible to remove a key and its corresponding value from a dictionary using del.

# Remove the key 'resist' from the dictionary
del webstersDict['resist']

FigureRemove the key ‘resist’ from the dictionary webstersDict.

In the Python Dictionary Methods section, you will see that you can also delete keys using the dictionary pop method.

Python Dictionary Methods

Python dictionaries have different methods that help you modify a dictionary. This section of the tutorial just goes over various python dictionary methods.

update method

The update method is very useful for updating multiple key values pairs at a time. It takes a dictionary as an argument.

# Using update method to add two key value pairs at once
webstersDict.update({'ran': 'past tense of run',
                     'shoes': 'plural of shoe'})

FigureAdded the keys ‘ran’ and ‘shoes’ to the dictionary.

get method

# Define a dictionary
storyCount = {'is': 100,
              'the': 90,
              'Michael': 12,
              'runs': 5}

The get method returns a value for a given key. If a key doesn’t exist, the dictionary will by default return None.

# Since the key 'Michael' exists, it will return the value 12
storyCount.get('Michael')

FigureSince the key ‘Michael’ exists, it returns the value 12. If ‘Michael’ didn’t exist, it would return None.

The method is very useful to look up keys you don’t know are in the dictionary to avoid KeyErrors.FigureThey key ‘chicken’ does not exist.

You can also specify a default value to return if the key doesn’t exist.

# Make default value for key that doesn't exist 0.
storyCount.get('chicken', 0)

FigureYou can see the usefulness of this method if you try a Python Word Count.

pop Method

The pop method removes a key and returns the value.

storyCount.pop('the')

FigureDictionary before and after removing the key ’the’ from the dictionary.

keys Method

The keys method returns the keys of the dictionary.

storyCount.keys()
Figure

values Method

The values method returns the values in the dictionary.

storyCount.values()

items Method

The items method returns a list like object of tuples where each tuple is of the form (key, value).

webstersDict.items()
Figure

Iterate through a Dictionary

You can iterate through the keys of a dictionary by using a for loop.

for key in storyCount:
   print(key)

FigureIterate through the keys of the dictionary.

You also iterate through the keys of a dictionary by using the keys method.

for key in storyCount.keys():
   print(key)

FigureIterate through the keys of the dictionary.

The for loop below uses the items method to access one (key, value) pair on each iteration of the loop.

for key, value in webstersDict.items():
    print(key, value)

FigureIterate through the key, value pairs of a dictionary.

If you have difficulty understanding this section, I recommend watching the following video.

Closing Remarks

Please let me know if you have any questions either here or through Twitter! The next post, Python Word Count will review Python dictionary methods, list manipulations, and string manipulations. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. Here is a free preview video.

Original Source

Feature image credit: AnalyticsInsights

The post Python Dictionary Guide: 10 Python Dictionary Methods & Examples appeared first on Big Data, Data Analytics, IOT, Software Testing, Blockchain, Data Lake – Submit Your Guest Post.

Leave a Comment

Get the BPI Web Feed

Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

Copy/Paste this code in your website html code:

<iframe src="https://www.businessprocessincubator.com/content/python-dictionary-guide-10-python-dictionary-methods-examples/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

Customizing your BPI Web Feed

You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

Customizing the Content Filter
On any page, you can add filter criteria using the MORE FILTERS interface:

Customizing the Content Filter

Customizing the Content Sorting
Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

Get the BPI Web Feed

Some integration examples

BPMN.org

XPDL.org

×