Dictionaries in Python

One of Pythons Four Main Data Structures

Python is a programming language that is very easy to understand and learn. Without much of the confusing syntax and complex object-oriented code of languages like Java, no wonder it’s (debatably) the most popular programming language out there. Python has all the essential tools other languages have for programmers of all skill levels. One of these tools is the Dictionary. The Dictionary is one of Python’s four built-in Data Structures. It is a tool similar to HashMaps and other order pair tools across different programming languages. This paper will entirely revolve around Dictionaries, what they are, how to use them, and how they came to be.

http://www.trytoprogram.com/python-programming/python-dictionary/

What is a Dictionary?

To understand what a Dictionary is, we first need to dive into a few subtopics and look into a few definitions. As I’ve mentioned previously, The Python Dictionary is one of four built-in Data Structures or Containers in Python. It is similar to other Data Structures in other languages that revolve around mapping Keys to Values. It is often compared to the HashMap in Java, and for a good reason. They are practically interchangeable, and both carry out the same jobs using very similar methods. They use a HashTable that maps specific Keys to specified Values to make Key-Value Pairs. To sum it up, a Dictionary is an Associative Array that has a HashTable running in the background that you can use to make Key-Value Pairs that map specific Keys to their designated Values.

Where did they come from?

We learned what Dictionaries are, but how did they and their components come to be? Dictionaries themselves came out with the first version of Python (version 0.9.0) near the end of the second month of the year 1991. They were among all the first basic Data Structures, Functions, and Value Types of early Python, and they’ve stuck since. Dictionaries are based heavily on the concepts of earlier Data Structures that used HashTables, such as the Stl Map from the C++ language, which came out in 1985. HashTables have been used since (at the very least) 1962, in the language SNOBOL4. Some even say that HashTables, or more specifically, Key-Value Pairs, have been used since the year 1837.

The Analytical Engine and Early Computer Languages

Now, what does THE Analytical Engine have to do with modern-day HashTables? The answer to this question is Key-Value Pairs. Back then, coding was done through Punch Cards, which used an early form of Binary digits, with holes punched into them. These cards would be used with Assembly Language and later with high-end languages like Fortran, which ran IBM 026 and IMB 056; both computers dealt with Punch Cards. They had Punch Cards since the Analytical Engine, then that means using the ten digits binary Value, they could have had Key-Value Pairs as far back as 1839. Key-Value Pairs have been used since 1962, and they may have been used even earlier.

Let’s get back on topic.

The last few sections have been a bit off-topic since it was the Dictionary in Python we are talking about here, not HashTables or Key-Value Pairs in the 19th century. I wanted you to get from this that Key-Value Pairs have been around for a long time, and the Dictionary is heavily tied in with this origin (so is the HashTable, the Associative Array, and every other similar Data Structure). Next, I want to talk about what makes Dictionaries different from Arrays in Java or just Lists in Python. I am also going to talk about the benefits and downsides of Dictionaries and their uses on specific projects. But before that, I need to talk about other forms of Data Structures.

Data Structures

In Python, there are three Data Structures besides the Dictionary. Those are the List, Tuple, and Set. Examples of Data Structures outside of Python are Vectors and Slt Maps in C++ and Arrays and HashMaps in Java. Let’s quickly summarize what they do. Lists are general-purpose, unoptimized containers that are flexible but lacking efficiency. Tuples are containers that store fixed Values, and they are faster at accessing those Values than Lists (they also work in sequential order). Sets are speedy at accessing Values and great for math operations, but they cannot duplicate and are unordered. Arrays are similar to Lists, but they are faster and less flexible. As you can see, each Data Structure has its use, be it niche or substantial. This does not exclude the Python Dictionary.

How Do Dictionaries Compare?

I have mentioned this before, but Dictionaries are a type of Data Structure/container that stores Values. I have already said this before too, but it is “unique” because of its Key-Value Pairs. This means it has its Pros and Cons that come with having Name/Key/Field Value Pairs, and because it’s a Linked List. For example, compared to an Array, a Python Dictionary takes up much less space to store the same amount of data, but it is noticeably slower at accessing that data.

Dictionaries (and in general containers that use HashTables and Keys) are slower at accessing store Values. The reason for this is that a Dictionary is a linked List, meaning every single section of the container is spread out, and their location must be accessed through each container, one by one. So every time you want to access a specific value, the computer will have to go through the entire Dictionary until it reaches the container you’re looking for.

The Coding

Before discussing the more complicated stuff you can do with Dictionaries, let’s first figure out the basics. Those are the syntax and commands you need to know to utilize Dictionaries, even on a fundamental level. By typing a = {}, you create a Dictionary that can be filled with Keys and Values that correspond with them. These Keys can be Strings, Integers, Tuples, Functions, Floats, Etc. They cannot be Lists or Dictionaries, and you can’t have the same Key appear twice in the same Dictionary. Values, on the other hand, can be just about anything.

Example: fruit = {‘name’: ‘apple’, ‘color’: ‘red’, ‘dishes’: [‘apple pie’, ‘apple tart’, ‘caramel apple’]}. The Keys in this case are the Strings “fruit”, “color”, and “dishes”. The Values are the strings “apple”, “red” and The List “[‘apple pie’, ‘apple tart’, ‘caramel apple’]”.

General Commands

Now that you can create a Dictionary and know its contents, the next step would be to add and extract those Values using the corresponding Keys. You can print the entire Dictionary by typing print(fruit) or whatever you named your Dictionary as. To print specific things from your Dictionary, you can use the command print(fruit[‘color’] to get the output “red.” With this command, I extracted the color of “apple” by calling the Key “color,” which has the value of “red”. You can also print only the Keys with print(fruit.Keys()) or just the Values with print(fruit.Values()). To add an item to the Dictionary, you can use the command fruit[‘taste’] = ‘sweet’. Or update the Values of the Dictionary using the command fruit.update({‘taste’: ‘sour’}). You can also delete an item with the command del fruit[‘taste’].

Extra Commands

You already know the general commands you can use with Dictionaries, so let’s look at some more niche commands. One example of this would be the .get

This command can grab certain values without the risk of getting an error if the Key you called does not exist. Example: print(fruit.get(‘name’)). You can also edit the end of the .get command to decide what you want to happen if a Key does not exist.

Example:print(fruit.get(‘flavor’, (‘No Key Found’))).

Another example would be the .pop command which deletes a Value from a Dictionary, but that Value can be saved before it’s gone completely.

Example: variable = fruit.pop(‘color’).

You can also edit the end of the .get command to decide what you want to happen if a Key does not exist.

Example:print(fruit.get(‘flavor’, (‘No Key Found’))).

General Implementations

Dictionaries are useful when you need to add specific Values from specific categories to keep track of the properties of certain Variables and items. By this, I mean you can assign certain Values to certain Keys in certain Dictionaries. You can also extract those Values to assign them to Variables or add them to a List. An example of this would be multiple Dictionaries for each student in a class. With Keys for their names, heights, hair colors, eye colors, or whatever you need to keep track of each student. You can then use this information with if statements and for loops to compare all the student’s heights or count the number of students with green eyes or brown hair. For loops work great with Dictionaries. You can extract each Value in a Dictionary using the i in name.Values():, each Key with the command for i in name.Keys(): , or each item (Key and value) using for i in name.items():. You can combine for loops and if statements to filter Dictionaries, add Values, delete Values, find Values, and combine all of this to make quizzes, tests, fill up files, and make all sorts of applications.

Take-Away

Dictionaries are one of the many essential tools that Python and many other coding languages out there offer to its users. It is a basic HashMap that can store all sorts of Values and data types. It might seem basic, but you can say the same thing about the rest of the tools. After all, the essence of programming is putting a bunch of simple inputs and outputs together into a fine-tuned machine that uses all the sums of its parts to calculate and complete a task no one person could do on their own. Top-of-the-line programmers use dictionaries to keep track of things that Lists and Arrays can’t keep up with. If you ever need a flexible storage system that is entirely scalable and friendly to on-the-fly editing, then the Python Dictionary might be for you.

--

--

--

Old, Current, and new programming languages.

Recommended from Medium

Why MASA is the future?

0-From ASP.NET to Flutter — The web coder path to Flutter

Coffee you will need

Antalya Konyaaltı Sarısu da Dağ Manzaralı Residence Daireler

Github Copilot, the AI we don’t want

Using “WITH” in SQL

A Data Scientist Makes A Website

Managing state and logging chat history in Microsoft bot framework

Road to the C

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Seattle Web Design

Seattle Web Design

Seattle Web Design Agency

More from Medium

Python Basics: 10 assignment operator

Tkinter GUI Programming

Objectively a mutant.

Pattern 8 : Tree Depth First Search