Python’s Most Powerful Data Type

Everything you ever need to know about Python dictionaries

Erik van Baaren
Python Land

--

Old books
Photo by Syd Wachs on Unsplash.

The dictionary is one of Python’s most powerful data types. In other programming languages and computer science in general, dictionaries are also known as associative arrays. This is because they allow you to associate keys with values.

Creating a Dictionary

Let’s look at how we can create and use a dictionary in the Python REPL:

>>> phone_nrs = { 'Jack': '070-02222748', 'Pete': '010-2488634' }
>>> an_empty_dict = { }
>>> phone_nrs['Jack']
'070-02222748'

The first dictionary associates keys (names like Jack and Pete) with values (their phone numbers). The second dictionary is an empty one.

Now that you’ve seen how to initialize a dictionary, let’s see how we can add and remove entries to an already existing one:

>>> phone_nrs['Eric'] = '06-10101010'
>>> del(phone_numbers['Jack'])
>>> phone_nrs
{'Pete': '010-2488634', 'Eric': '06-10101010'}

Valid Dictionary Values

You can put anything in a dictionary. You’re not limited to numbers or strings. In fact, you can put dictionaries and lists inside your dictionary and access the nested values in a very natural way:

--

--