Working with Dictionaries in Python

This definitive guide to Python Dictionaries will help you learn everything you know about the Python Dictionary and its capabilities. You’ll also learn how to use the dictionary to establish word frequency.

A mutable dictionary is a built-in Python Data Structure. In spirit, it’s similar to List, Set, and Tuples. It is, however, not indexed by a sequence of numbers but keys and can be thought of as associative arrays. It consists of a key and a value on a more abstract basis. The Dictionary in Python represents a hash-table implementation.

Python dictionaries are similar to lists in that they can grow in size as more items are added.
However, unlike lists, they have a lightning-fast lookup time. The key is everything you need to know to get the value, e.g., the person and the phone number.

This post will go over why dictionaries are so useful and when you should use them.

Since you use it to map key-value pairs, the Python dictionary is also known as a “mapping.” In other words, a value is assigned to a key at any location in a dictionary.

The way you look up words in a dictionary is with keys. They must be special for you to find the right value by using them for lookup. Since you don’t use lookup values, they can be duplicated, as in the example above.

How Dictionaries work in Python

Dictionary keys must be an entity to which a hash value can be assigned. Tuples and strings are examples of immutable properties. They can’t be reversed after they’ve been made.

Lists, collections, and dictionaries are examples of mutable objects that cannot be assigned as a key because they can be modified later without duplicating.

Integers, floats, strings, tuples, and even frozen sets are immutable objects that cannot be modified without copying the entire object and generating a new object ID.

This ensures consistency by ensuring that you’ll get the same result every time you use the object as a lookup. As a result, these objects can be used to find the key-value pair and generate a consistent hash value.

Keys are “hashed.” Behind the scenes, thus Python dictionaries are implemented as a hash table. The dictionary employs each key’s hash function to convert some of the key’s data into an integer known as a hash value.

The hash value indicates which bucket the key-value pair belongs in. This way, you’ll know exactly which bucket to check any time you need to lookup or locate the key-value pair. That’s how keys help you save time while looking up a value.

When do I need to consult a dictionary?

Dictionaries are useful for quick lookups as well as storing unique keys and their values.
So, when do you think you’ll come across a dictionary in a real codebase? A dictionary can be handy when building a data store or database in vanilla Python.

Wondering what keys are?

Worry no more. Keys are data types that cannot be changed – data types that can be strings or numbers. A key, on the other hand, cannot be a mutable data form like a list. Within a dictionary, keys are special and cannot be duplicated; if the same key is used more than once, subsequent entries will replace the previous value.

They are the main links to the value, forming a map-like structure. Remove the keys from the picture for a moment, and you’re left with a data structure containing a sequence of numbers. As a result, each location in dictionaries contains a key: value pair.

A dictionary is represented by a pair of curly braces with key: value pairs separated by a comma within.

Dictionary’s syntax is as follows:

dictionary = {"first_key": "first_value", "second_key": "second_value", "third_key": "third_value"}

Unique Keys

Now that you know that keys in a dictionary must be special, let’s break it down with an example.

_unique_dictionary= {"a": "apple", "o": "oval", "g": "game"}
print(_unique_dictionary)

So far, everything seems to be in order. Your first dictionary output was successfully printed. Let’s try again with a different value for the key g and see what happens.

_unique_dictionary = {"a": "apple", "o": "oval", "g": "game", "g": "george"}
print(_unique_dictionary)

Value george overwrote the g previous value game, as predicted.

Unique Keys
Unique Keys

 

Keys that can’t be changed

Let’s take a look at what happens if you try to make the key a mutable data type.

dictionary_immutable = {["a","b","c"]: "apple", "o": "oval", "g": "game", "g": "george"}
print(dictionary_immutable )
Keys that cannot be changed
Keys that cannot be changed

You can see from the above output that defining the dictionary’s first key as a list causes a TypeError since dictionary keys must be immutable types, and the list is a mutable type.

using tuple instead of a list in a dictionary

However, since a tuple is an immutable data form, there is a workaround: replace the list with a tuple.

dictionary_immutable = {("a","b","c"): "apple", "o": "oval", "g": "game", "g": "george"}
print(dictionary_immutable)
using tuple instead of list in a dictionary
using tuple instead of list in a dictionary

How to look for a Key in a Dictionary

It’s also advantageous to see if a key already exists in a dictionary (remember that keys have to be unique).

According to Python’s documentation, I am using the in keyword to see if a single key is in the dictionary.

>>> ages = {"Tom": 80, "Viola": 34, "Tess": 67}
>>> "Tess" in ages
True
>>> "Tom" in ages
True
>>> "Lulu" in ages
False

The in operator does not check the values. Instead, it only checks the keys. For example, in the sample below, False will be returned.

>>> 80 in ages
False

We’re looking to see if the key 80, not the value, is in the dictionary. As a result, the expression returns False. Luckily, there is a workaround.

With <dict>.values() , you can use the in operator to see if a value is in a dictionary ().

>>> ages = {"Tom": 80, "Viola": 34, "Tess": 67}
>>> 67 in ages.values()
True
>>> 10 in ages.values()
False

All these examples are illustrated in the diagram below.

How to look for a Key in a Dictionary
How to look for a Key in a Dictionary

How to access Keys and Values

Now that you know how to make dictionaries let’s look at how to get the keys and values.

Use .items() method

The.items() method returns a list of dict_items in the form of a key, value tuple pair, which you can use to access the key-value pair. Note that this method returns all the entire list in a given dictionary except where a similar key is used ā€“ the last one is displayed. For instance, in our example below, george will be returned for key ā€˜gā€™ instead of both or game.

_unique_dictionary= {"a": "apple", "o": "oval", "g": "game","g": "george"}
_unique_dictionary.items()
Use .items() method
Use .items() method

use for loop to access keys and values

You could use a for loop on the dictionary or the. keys() and. values() methods to access keys and values separately.

for key, value in _unique_dictionary.items(): #accessing keys 
Ā  Ā print(key,end=',')

for key, value in _unique_dictionary.items(): #accessing values 
Ā  print(value,end=',')

use for loop to access keys and values
use for loop to access keys and values

accessing dictionary keys using the method .keys()

_unique_dictionary= {“a”: “apple”, “o”: “oval”, “g”: “game”,”g”: “george”}
_unique_dictionary.keys()

accessing dictionary keys using the method .keys()
accessing dictionary keys using the method .keys()

accessing dictionary values using the method .values()

_unique_dictionary= {“a”: “apple”, “o”: “oval”, “g”: “game”,”g”: “george”}
_unique_dictionary.values()

accessing dictionary values using the method .values()
accessing dictionary values using the method .values()

pass a key to the dictionary as a parameter

You could also access a value by passing a key to the dictionary as a parameter.

_unique_dictionary= {"a": "apple", "o": "oval", "g": "game","g": "george"}
_unique_dictionary['a']
_unique_dictionary['g']
pass a key to the dictionary as a parameter
pass a key to the dictionary as a parameter

Dictionary Elements: Changing and Adding

Dictionaries are subject to change. Using the assignment operator, we can create new items or adjust the value of existing ones.

If the key already exists, the original value will be changed. If the key is missing, the dictionary is updated with a new (key: value) pair.

# adding and changing elements in a dictionary

dict_elements= {'fname': 'Thomas', 'age': 42}

# update value
dict_elements['age'] = 36

#Output: {'age': 36, 'name': 'Thomas'}
print(dict_elements)

# add item
dict_elements['address'] = 'CapitalHill'

# Output: {'address': 'CapitalHill', 'age': 36, 'name': 'Thomas'}
print(dict_elements)
Dictionary Elements: Changing and Adding
Dictionary Elements: Changing and Adding

Removing elements from a Dictionary

Using the pop() method, we can delete a specific item from a dictionary. This method returns the value after removing an object with the given key.

The popitem() method removes and returns any (key, value) item pair from the dictionary. On the other hand, the clear() method can be used to delete all of the objects at once.

Also, the del keyword may be used to delete individual items or the entire vocabulary.

# dictionary creation
item_names = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five"}

# return the value of the removed item
print(item_names.pop(4))

# print items in the dictionary
print(item_names)

# return (key,value) after removing an arbitrary item
print(item_names.popitem())

# print the new list of items
print(item_names)

# removing all items
item_names.clear()

# Output: {}
print(item_names)

# dictionary deletion
del item_names

# Throws Error
print(item_names)
elements removal from a dictionary
elements removal from a dictionary

The Nested Dictionaries

It’s easy to make a nested dictionary. You pass a dictionary within a dictionary or put it another way; a dictionary is transferred as a value to a key of the main dictionary in the nested dictionary.

You’ll make a subjects dictionary inside a nested dictionary, school_nested_dictionary, in this phase.

school_nested_dictionary = {"subjects":{"Languages": "English", "Sciences": "Physics"},"teachers":"permanent","support":"cooks"}

print(school_nested_dictionary)


school_nested_dictionary['subjects']['Languages']

school_nested_dictionary['subjects']['Sciences']

school_nested_dictionary['teachers']
The Nested Dictionaries
The Nested Dictionaries

Comprehension of Dictionaries

Dictionary comprehensions can be used to construct dictionaries from any combination of key and value phrases. It’s a quick and easy way to make dictionaries, and it’s also quicker than traditional loop implementations.

Example1: comprehension of dictionaries

#example1_comprehension.py
import time
initial_time = time.time()
comprehension_dict = {j: j**20 for j in range(500000)}
print(time.time() - initial_time)
Example1: comprehension of dictionaries
Example1: comprehension of dictionaries

Example2: comprehension of dictionaries

#example2_comprehension.py

import time
initial_time = time.time()
final_time =" "
comprehension_dict = dict()
for j in range(500000):
comprehension_dict [j+1] = j**20
final_time = time.time()
print(final_time - initial_time)
Example2: comprehension of dictionaries
Example2: comprehension of dictionaries

islice in comprehension of dictionaries

Let’s print the comprehension_dict dictionary’s first twenty key: value pairs. You’ll do this by importing islice from the itertools built-in package and specifying n as the number of key-value pairs you’d like to get.

import time
from itertools import islice

comprehension_dict = {j: j**20 for j in range(500000)}
first_20_keys = list(islice(comprehension_dict .items(),20))

print(first_20_keys )
islice in comprehension of dictionaries
islice in comprehension of dictionaries

As you can see from the two examples of dictionary implementations above, dictionary comprehension wins by a small margin in terms of execution time. You’ll find that as the range parameter is increased, the difference in time increases as well.

Frequency of Words

With the aid of a dictionary, we can construct a word frequency from a set of written texts, in this case, a string of text, also known as corpus.

# frequency_of_words.py

my_sentence = 'doing all i do about learning python and programming is vital for my overall growth in python as well as my career as a programmer'

frequency_of_words = dict()
word_corpus = str(my_sentence).split()
for _word in range(len(word_corpus)):
if word_corpus[_word] not in frequency_of_words:
frequency_of_words[word_corpus[_word]] = 1

else:
frequency_of_words[word_corpus[_word]] += 1


print(frequency_of_words)
Frequency of Words
Frequency of Words

Sorting a Dictionary in Python

Python dictionaries don’t have any kind of order. This also means they can’t be sorted in the same way a Python list can. Python dictionaries can be represented in sorted form by programmers. We’ll show you how to make a sorted performance in this segment.

The data could be sorted in either a natural or reverse order by programmers. They have the option of sorting the data by keys or values.

Sorting by Keys using sort() method
#sort_by_keys_using_sort_method.py

count_by_profession = { "lawyers": 7, "teachers": 3, "musicians": 2, "engineers": 1, "librarians": 4, "politicians": 5 }

prof_items = list(count_by_profession.keys())
prof_items.sort()

for k in prof_items:
joined_items =(k,str(count_by_profession[k]))
print(": ".join(joined_items))
Sorting by Keys using sort() method
Sorting by Keys using sort() method

In the loop, we print the sorted keys along with their dictionary values.

Sorting dictionary items by their keys

The keys are used to sort the products dictionary. However, the built-in sorted() function allows for more effective sorting, as shown below.

# sort_dictionary_items_keys.py

count_by_profession = { "lawyers": 7, "teachers": 3, "musicians": 2, "engineers": 1, "librarians": 4, "politicians": 5 }

print("###### sorting by key in ascending") 
for key in sorted(count_by_profession.keys()):
print("{0}: {1}".format(key, count_by_profession[key]))

print("###### sorting by key in descending")

for key in sorted(count_by_profession.keys(), reverse=True):
print("{0}: {1}".format(key, count_by_profession[key]))
Sorting dictionary items by their keys
Sorting dictionary items by their keys
Sorting dictionary items by their values

The following example sorts the items by their values.

# sort_dictionary_items_values.py

count_by_profession = { "lawyers": 7, "teachers": 3, "musicians": 2, "engineers": 1, "librarians": 4, "politicians": 5 }

print("############### sort by value in ascending")
for key, value in sorted(count_by_profession.items(), key=lambda pair: pair[1]):

print("{0}: {1}".format(key, value))

print("############### sort by value in descending")

for key, value in sorted(count_by_profession.items(), key=lambda pair: pair[1], reverse=True):

print("{0}: {1}".format(key, value))
Sorting dictionary items by their values
Sorting dictionary items by their values

Dictionary Methods in Python

The methods that can be used with a dictionary are mentioned below. Some of them have already been listed in the previous paragraphs.

clear()

clear() is a method that removes all things from the dictionary.

Copy()

A shallow copy of the dictionary is returned by copy().

fromkeys (seq[, v])

Returns a new dictionary with seq’s keys and v’s value. Besides, it defaults to None.

get (key[,d])

The value of the key is returned. Returns d if the key doesn’t exist. Besides, it also defaults to None.

items()

items() returns a new object containing the dictionary items in (key, value) format.

keys()

keys() returns a new object containing the keys of the dictionary.

pop(key[,d])

The function pop(key[,d]) removes the item associated with the key and returns its value, or d if the key cannot be located. It raises KeyError if d is not given and the key is not found.

popitem()

popitem() is a function that removes and returns an arbitrary item (key, value). If the dictionary is null, it raises a KeyError.

setdefault(key[,d])

If the key is found in the dictionary, it returns the corresponding value. If not, returns d and inserts the key with a value of d. It also defaults to None.

update ([other])

Overwrites existing keys in the dictionary with key/value pairs from other sources.

values()

The function ensures that a new object containing the dictionary’s values is returned.

Here are a few examples of how these techniques can be used.

# common_methods_dictionary.py
subject_marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(subject_marks)

for mark in subject_marks.items():
print(mark)

# Output: ['English', 'Math', 'Science']
print(list(sorted(subject_marks.keys())))
Common Methods in a Dictionary
Common Methods in a Dictionary

Built-in Dictionary Functions

All(), any(), len(), cmp(), sorted(), and other built-in functions are widely used with dictionaries to perform various tasks.

all()

If all keys in the dictionary are True, all() returns True. It also returns True if the dictionary is empty.

any()

If any key in the dictionary is valid, any() returns True. On the contrary, it returns False if the dictionary is empty.

len()

len() returns the dictionary’s length that is the number of items.

sorted ()
The sorted() function returns a new sorted list of dictionary keys.

The subsequent section presents examples of functions built-in so that they work with dictionaries.

#dictionary_built_in_functions.py

square_of_numbers = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# expected: False
print(all(square_of_numbers ))

# expected: True
print(any(square_of_numbers ))

# expected: 6
print(len(square_of_numbers ))

# expected: [0, 1, 3, 5, 7, 9]
print(sorted(square_of_numbers ))
Examples of Dictionary Built-in Functions
Examples of Dictionary Built-in Functions

Conclusion

A dictionary is an ordered, changeable data structure that does not allow duplicates. Besides, dictionaries are now ordered as of Python 3.7. However, Dictionaries in Python 3.6 and earlier are not ordered. When we claim that dictionaries are ordered, we’re referring to the fact that the objects are arranged in a certain order that will not alter. On the contrary, unordered means that the objects aren’t in any particular order, and you can’t use an index to find them.

The distinctive factor is the curly brackets used to write dictionaries, which have keys and values.

Dictionary objects in Python are iterable objects with key-value pairs that can be added, removed, or modified. Further, methods like.keys(),.values(), and.items() may be used to access dictionary components (). Since dictionaries are iterable structures, loops and dictionary comprehensions are possible in Python.

Changeable dictionaries are editable, which means we can add, delete, or change things after they’ve been created. Just remember that duplicates aren’t allowed in dictionaries – two objects with the same key aren’t allowed.

Any data type can be used as a value in a dictionary item. However, understanding the properties of a selected category is helpful when selecting one. Choosing the right form for a given data set will result in meaning retention and increased productivity and protection.

Similar Posts

Leave a Reply

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