Python Dictionary and Dictionary Strategies

By Michael Galarnyk, Knowledge Scientist

This Python Dictionary tutorial covers:

  • How you can Outline a Dictionary
  • How you can Entry Values in a Dictionary
  • How you can Add, Replace, and Delete Keys from a Dictionary
  • Dictionary Strategies
  • How you can Iterate by means of a Dictionary

With that, let’s get began.

 

Outline a Dictionary

 
Dictionaries are written inside curly brackets .

Figure

Outline a dictionary. Keys are in crimson. Values are in blue.

 

# Outline a dictionary code 
webstersDict = 

The dictionary webstersDict used strings as keys within the dictionary, however dictionary keys could be any immutable information kind (numbers, strings, tuples and many others). Dictionary values could be absolutely anything (int, lists, capabilities, strings, and many others).

For instance, the dictionary beneath, genderDict has ints as keys and strings as values.

# Outline a dictionary
genderDict = 

An vital level to emphasise is that in case you attempt to make a key a mutable datatype (like an inventory), you’ll get an error.

# Failure to outline a dictionary
webstersDict = (1, 2.zero): 'tuples could be keys',
                1: 'ints could be keys',
                'run': 'strings could be keys', 
                ['sock', 1, 2.0]: 'lists can NOT be keys'
Figure

Failure to outline a dictionary with an inventory as a key. Lists are NOT immutable

 

 

Entry Values in a Dictionary

 
To entry a dictionary worth, you need to use sq. brackets [].

For instance, the code beneath makes use of the important thing ‘marathon’ to entry the worth ‘a running race that is about 26 miles’.

# Get worth of the 'marathon' key
webstersDict['marathon']
Figure

Entry the important thing ‘marathon’

 

Understand that you’ll get a KeyError in case you attempt to entry a price for a key that doesn’t exist.

# Attempt to get worth for key that doesn't exist
webstersDict['nonexistentKey']
Figure

KeyError will outcome in case you attempt to search for a key that doesn’t exist.

 

Within the Dictionary Strategies part, you will notice the utility of utilizing the dictionary methodology get to keep away from KeyErrors.

 

Add, Replace, and Delete Keys from a Dictionary

 

Add or Replace Key

 
You possibly can add a brand new key-value pair.

# add one new key worth pair to a dictionary
webstersDict['shoe'] = 'an exterior protecting for the human foot'
Figure

Add the brand new key ‘shoe’ to the dictionary. The brand new key ‘shoe’ is enclosed within the crimson rectangle.

 

You can too replace a key-value pair.

Figure

Replace the dictionary key ‘marathon’

 

Within the Dictionary Strategies part, you will notice which you could additionally add or replace a number of key worth pairs at a time utilizing the dictionary replace methodology.

 

Delete Keys from Dictionary

 
It’s potential to take away a key and its corresponding worth from a dictionary utilizing del.

# Take away the important thing 'resist' from the dictionary
del webstersDict['resist']
Figure

Take away the important thing ‘resist’ from the dictionary webstersDict.

 

Within the Dictionary Strategies part, you will notice which you could additionally delete keys utilizing the dictionary pop methodology.

 

Dictionary Strategies

 
Python dictionaries have completely different strategies that allow you to modify a dictionary. This part of the tutorial simply goes over numerous python dictionary strategies.

 

replace methodology

 
The replace methodology could be very helpful for updating a number of key values pairs at a time. It takes a dictionary as an argument.

# Utilizing replace methodology so as to add two key worth pairs without delay
webstersDict.replace('ran': 'previous tense of run',
                     'sneakers': 'plural of shoe')
Figure

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

 

 

get methodology

 

# Outline a dictionary
storyCount = 

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

# For the reason that key 'Michael' exists, it would return the worth 12
storyCount.get('Michael')
Figure

For the reason that key ‘Michael’ exists, it returns the worth 12. If ‘Michael’ didn’t exist, it could return None.

 

The strategy could be very helpful to search for keys you don’t know are within the dictionary to keep away from KeyErrors.

Figure

They key ‘chicken’ doesn’t exist.

 

You can too specify a default worth to return if the important thing doesn’t exist.

# Make default worth for key that does not exist zero.
storyCount.get('rooster', zero)
Figure

 

 

pop Methodology

 
The pop methodology removes a key and returns the worth.

Figure

Dictionary earlier than and after eradicating the important thing ’the’ from the dictionary.

 

 

keys Methodology

 
The keys methodology returns the keys of the dictionary.

Figure

 

 

values Methodology

 
The values methodology returns the values within the dictionary.

 

objects Methodology

 
The objects methodology returns an inventory like object of tuples the place every tuple is of the shape (key, worth).

Figure

 

 

Iterate by means of a Dictionary

 
You possibly can iterate by means of the keys of a dictionary through the use of a for loop.

for key in storyCount:
   print(key)
Figure

Iterate by means of the keys of the dictionary.

 

You additionally iterate by means of the keys of a dictionary through the use of the keys methodology.

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

Iterate by means of the keys of the dictionary.

 

The for loop beneath makes use of the objects methodology to entry one (key, worth) pair on every iteration of the loop.

for key, worth in webstersDict.objects():
    print(key, worth)
Figure

Iterate by means of the important thing, worth pairs of a dictionary.

 

If in case you have issue understanding this part, I like to recommend watching the next video.

 

Closing Remarks

 
Please let me know when you have any questions both right here or by means of Twitter! The following publish, Python Word Count will evaluation dictionary strategies, list manipulations, and string manipulations. If you wish to learn to make the most of the Pandas, Matplotlib, or Seaborn libraries, please take into account taking my Python for Data Visualization LinkedIn Learning course. Here’s a free preview video.

 
Bio: Michael Galarnyk is a Knowledge Scientist and Company Coach. He at the moment works at Scripps Translational Analysis Institute. You’ll find him on Twitter (https://twitter.com/GalarnykMichael), Medium (https://medium.com/@GalarnykMichael), and GitHub (https://github.com/mGalarnyk).

Original. Reposted with permission.

Associated:

About the Author

Leave a Reply

Your email address will not be published. Required fields are marked *