Python Dictionary Usage – Python 3 Tutorial for Beginners #09

Python dictionary is an easy to use data structure. In the previous tutorial I covered creating, setting values, deleting values and checking existence of a key. For this tutorial I am going to cover how to access keys, values and items, how to use dictionary comprehension and many more.

Using Python Dictionary as a Mapping

Have you heard of Morse code? Of course, you have. Let’s see how we can use a dictionary to transform a single phrase in to Morse code. You’ll see that using dictionaries in Python 3 is a piece of cake.

First of all we need to create a mapping such as this:

morse =  {"A": ".-",         "B": "-...",       "C": "-.-.",       "D": "-..", 
          "E": ".",          "F": "..-.",       "G": "--.",        "H": "....", 
          "I": "..",         "J": ".---",       "K": "-.-",        "L": ".-..", 
          "M": "--",         "N": "-.",         "O": "---",        "P": ".--.", 
          "Q": "--.-",       "R": ".-.",        "S": "...",        "T": "-", 
          "U": "..-",        "V": "...-",       "W": ".--",        "X": "-..-", 
          "Y": "-.--",       "Z": "--.."}

Now to convert given phrase to morse-code we can do the following:

Python 3 Dictionary Used to Calculate Morse Code
Python 3 Dictionary Used to Calculate Morse Code

You can grab the complete snippet here.

Accessing All Keys of a Dictionary

When using dictionaries in Python, you’ll find that there are situations where you need to access all the keys stored in a dictionary. Here’s how you do it:

dict_object.keys()

This will return a view object. View object represent a view of the dictionary. Whenever the original dictionary object is updated view objects will also show it accordingly.

Note: Do not depend on the order of the elements of dict’s items, values and keys. Use OrderedDict if you want to preserve insertion order.

Let’s how to use this knowledge in GIF format:

Python 3 Dictionary Keys
Python 3 Dictionary Keys

Accessing All Values of a Dictionary

You can also access stored values of a dictionary object. Instead of getting the keys and accessing values using the keys. You can get a view object containing values.

dict_object.values()

Time for some GIF action:

Python 3 Dictionary Values
Python 3 Dictionary Values

Accessing All Key-Value Pair Items of a Python Dictionary

There are situations that you simply need to iterate over a dictionary object. In such situations what you need to do is use the items() function to access all the key-value pairs stored in the dictionary.

dict_object.items()

Let’s see it in action:

Python 3 Dictionary Iterate
Python 3 Dictionary Iterate

Dictionary Comprehension

If you can produce a list of keys and values you can easily use dictionary comprehension to build a dictionary.

Dictionary Comprehension
Dictionary Comprehension

Let’s see it in action:

Python 3 Dictionary Comprehension in Action
Python 3 Dictionary Comprehension in Action

Alternative Dictionaries for Specific Tasks

When using dictionaries in Python, you’ll see that simple dict implementation is not always enough to do certain tasks. There are certain situations that you need special dictionary based classes for this.

Let’s use Python 3 defaultdict

There are certain situations that you need to have a default values filled in the dictionary. Common practice is to check if the key doesn’t exist and fill in the default value. You can simplify this using the convenient defaultdict implementation. It takes a function as a parameter to the constructor.

If you want to keep creating dictionaries as you go deep in to the structure you can try following method.

Python 3 deafultdict
Python 3 deafultdict

This is how it works:

Python 3 defaultdict trick
Python 3 defaultdict trick

Now, let’s try a simpler approach. This will create a new list as the default value. You can directly call the append method or any other list specific method directly on an dictionary value.

from collections import defaultdict
import json

m = defaultdict(list)
m["a"].append(1)
m["a"].append(2)
m["b"] # Simply access it to create an empty list

print(json.dumps(m)) # {"a": [1, 2], "b": []}

Want to use Python 3 Counter? Here’s how

One of the simplest things you’ll do when using dictionaries in Python is to count elements. See the previous tutorial to see how to do this using a plain old dict. Value of the Counter object is always an int. Let’s see how to count characters using Counter class.

from collections import Counter
text = "the quick brown fox jumps over the lazy dog"

c = Counter(text)
del c[' '] 
print(c.most_common(4))
print("1 count =", c['1'])

It is very easy all you need to do is pass in the sequence. In this case it is the text object. You can use any other sequences as well. You can get a list of most common elements or largest counts using most_common([count]) method. Count parameter is optional and if not provided will return all the counts.

Let’s use the following utility function to print a counter:

def print_counter(c):
    items = sorted(dict(c).items(), key=lambda x: x[0])
    items = ["{}:{}".format(x, y) for x, y in items]
    print(",".join(items))

Counters also have set like capabilities

Python 3 Counter
Python 3 Counter
print_counter(t + n) # Add counters
print_counter(t | n) # Union max of the counters
print_counter(t - n) # Subtract counters
print_counter(t & n) # Intersection min of counters

Unary operators provide short-cuts to adding an empty counter or to subtracting from an empty counter.

Python 3 Counter Unary Operators
Python 3 Counter Unary Operators

How to use Python 3 OrderedDict

Yet another dictionary type in Python 3 is OrderedDict. You can iterate on a standard dict object however you cannot expect or depend on the order of the items, keys or values. OrderedDict stores the insertion order and will iterate using the same method.

Note: Starting from Python 3.6, dict is also ordered. In a situation you need to preserve insertion order, for compatibility reasons and readability using OrderedDict is recommended. You should avoid depending on tiny implementation details to make your code future and past proof.

from collections import OrderedDict

d = OrderedDict()
d['x'] = "x"
d['a'] = "a"
d['z'] = "z"

print(d)

This will print the elements as following.

OrderedDict([('x', 'x'), ('a', 'a'), ('z', 'z')])

Let’s try Python 3 ChainMap

Want to look in multiple maps without combining them? You can use a ChainMap for this requirement. This is very useful if you want to keep different default values or to combine application level configurations and user level configurations.

from collections import ChainMap

app_config = {'border': 1, 'color': 'red', 'size': 100}
user_config = {'border': 2}

config = ChainMap(user_config, app_config)

print("Initial")
print(list(config.items()))

config['color'] = 'green'
print("After:: config['color'] = 'green'")
print(list(config.items()))

print("After:: del config['border']")
del config['border']
print(list(config.items()))

This will display following:

Initial
[('size', 100), ('color', 'red'), ('border', 2)]
After:: config['color'] = 'green'
[('color', 'green'), ('size', 100), ('border', 2)]
After:: del config['border']
[('size', 100), ('color', 'green'), ('border', 1)]

Let’s see how to use extra functionality provided by ChainMap:

ChainMap Cool Functions
ChainMap Cool Functions

That’s it for this tutorial. Stay tuned for more. Comment below if you have any questions.

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!

Like what you see? Subscribe to our email list and hit us with a like on our Facebook page to get the latest news updates and tutorials straight to your newsfeed!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.