Python Dictionary

A dictionary in Python is a collection of items accessed by a specific key rather than by index. What does this mean?

Imagine a dictionary in the real world… when you need to look up the meaning of a word, you try to find the meaning using the word itself and not the possible index of the word. Python dictionaries work with the same concept, the word whose meaning you are looking for is the key and the meaning of the word is the value, you do not need to know the index of the word in a dictionary to find its meaning.

Note: The keys in a dictionary have to be hashable.

Hashing is the process of running an item through a specific kind of function. This function is called a “hash function”. This hash function returns a unique output for a unique input value. Integers, floating point numbers, strings, tuples, and frozensets are hashable. While lists, dictionaries, and sets other than frozensets are not. Hashing is a somewhat complex topic and this is only the basic concept behind hashing.

You can initialize a dictionary in Python this way:

Python Dictionary Comprehension

Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.

A good list comprehension can make your code more expressive and thus, easier to read. The key with creating comprehensions is to not let them get so complex that your head spins when you try to decipher what they are actually doing. Keeping the idea of “easy to read” alive.

The way to do dictionary comprehension in Python is to be able to access the key objects and the value objects of a dictionary.

How can this be done?

Python has you covered! You can simply use the built-in methods for the same: