Skip to main content

python3 dictionary: introduction, creation, addition and deletion

 Introduction:

                     Photo by Dmitry Ratushny on Unsplash
 

We know that dictionary is one of the fundamental structures in python language. Dictionaries exist in the core of python structures; as the class objects are partially made by dictionary containing their information. I have been using python for more than 2 years now; and I have seen some good usage of dictionaries. Recently for a project, I solved a simple sounding yet, moderately complex problem using dictionaries heavily and revised some of the notions of pythonic writing of dictionaries along wise. This article will contain some of those understanding and best ways.

What is dictionary?

If you know what a dictionary is, then please skip to next section; but we will shortly define what is a dictionary and why would you like to use once. Dictionary is a unordered collection of values which are indexed. Dictionaries are mainly used in scenarios where you want to have constant time (O(1)) lookup. In an ideal case, dictionaries do provide such a constant time lookup; but in more real scenarios, they provide a linear time lookups. Lookup time and implementation of ideal hash tables in a dictionary is out of this article; but interested one can look here

In python3, an empty dictionary can be initiated using a simple 

dict = {}

You can also create a dictionary using the python dict() command; asin

empty_dict = dict()

creates a dictionary in empty_dict. Although it is known that {} is the faster method to initiate empty dictionaries.

As I said already, a dictionary is unordered and contains values that are indexed. Each value has a unique key in a dictionary but the reverse is not same. In standard terms, we define a dictionary by key: value pairs. Let's see a normal dictionary.

Photo by Dmitry Ratushny on Unsplashnormal_dict = {"harry":2, "shyambhu":3}

In this dictionary, the strings "harry" and "shyambhu" are the keys and their values are respectively 2 and 3. For getting the values corresponding to these keys, you can use the syntax dictionary[keys] = value; i.e. 

normal_dict["harry"] gives 2

normal_dict["shyambhu"] gives 3.

Now, you will also need to see all the keys and all the values. Using dictionary.keys() you can get an iterable containing all the keys. You can say print all the keys and their values like this:

for key in dictionary.keys():

    print(key,dictionary[key])

But there is a better way yet to do this. And that is called the items() method of a dictionary. In such a case, you can use this:

for key,value in dictionary.items():

    print(key,value)

And voila! that prints the keys and values. If you are a beginner, then you probably want to find a length of a dictionary; but there isn't one. So here our small detour to define dictionaries end.

Now, we will see little more advanced manipulations of dictionaries.

Additions of dictionaries:

One thing which is really easy in lists is that they can be added just using a "+" operator; but the same thing is not allowed for dictionaries; because of probable key collisions ( what happens if keys are same). 


 

Now, there will be practical need of adding dictionaries. When you are certain that there is no intersection of keys; or any of the values from each dictionary is fine to keep [i.e. no dictionary is superior and it is fine to choose at random which dictionary's value to keep when a key is common]; then you can use the update() command to add two dictionaries. The way it works is:

dict1.update(dict2) 

i.e. if you take a dict1 = {"harry":2, "shyambhu":3} and dict2 = {"food":10,"red":3}

then dict1.update(dict2) returns None and dict1 becomes 

{"harry":2, "shyambhu":3,"food":10,"red":3}

In a more complicated scenario; if a key is common; the value in dict1 is updated from dict2 i.e. dict2's values dominate in case of key intersection. Check this example below to see how it works with these 2 one keyed dictionaries.


 

You can also; do the following:

keys1 = set(dict1.keys())

keys2 = set(dict2.keys())

key_union = keys1.symmetric_difference(keys2)

key_intersections = keys1.symmetric_difference(keys2)

for key in key_union:

      #some rule

for key in key_intersections:

      #some rule

where you define the rules according to your use cases. Obviously this is when the built in updates would not work. As your python code will be slower than the built-in in most cases.

Now, we will see how we can delete a dictionary entry.

deletion:

For deletion of very few, I saw a bunch of methods; like creating new dictionaries or involving loops and other things; but when you clear all the non-sense methods and focus on real usage; del is the way to go. The syntax to delete a dictionary element  by key is 

del dictionary[key]

This is crisp; and involves just dropping that key. If you are using something else which is definitely not faster than this, use this. 

But this advise is wrong when you are deleting a significant number of keys; i.e. probably keeping only certain number of keys. In such a case, you should rewrite a new dictionary. Read this thread to understand about del in deeper level.

Next we will consider some specific dictionary creation processes; which are not that famous.

zipping and creating dict from 2 columned dataframe:

I will describe two dictionary creations; and will not comment about the speed guarantee as there maybe better methods than which I write here; but this is more on readable and small code.

scenario1: 

you are given two lists and you are wondering how to create a dictionary from two lists in python. In such a case, zip comes handy. Let's say the list which is supposed to be keys is lis1 and the values are in lis2 ; and lis1[i] corresponds to its value in lis2[i].

In such a case, dict_created = dict(zip(lis1,lis2)) is the easiest solution. Now this solution is known to many among us probably; but what you may still be doing wrong is the same thing in case of a dataframe.

scenario2:

You are given a two column dataframe and you are wondering how to create a dictionary from a two column dataframe; where each row is nothing but a key followed by its value.

In such a scenario, with pandas and numpy blazing in your script; you may end up forgetting such a easy oneliner solution. But the scenario1 is nothing different from scenario2.

In this case, let's say you have a dataframe df and the two columns are lis1 and lis2; then 

dict_created_2 = dict( zip( df[lis1].tolist(), df[lis2].tolist() ) ) 

is the easy solution to do this. 

You may also employ some solution using dataframe iteration of row by row; but that will not be more efficient than this solution for most cases. I have not tested this scenario in details and therefore will not guarantee as I said before.

Conclusion: 

So these are the things which I found interesting today about dictionary and revisited some of these because I forgot some of the commands. Let me know if you found this useful; and surf the index page for more contents to your liking.

Thanks for reading!

Comments

Popular posts from this blog

Mastering SQL for Data Science: Top SQL Interview Questions by Experience Level

Introduction: SQL (Structured Query Language) is a cornerstone of data manipulation and querying in data science. SQL technical rounds are designed to assess a candidate’s ability to work with databases, retrieve, and manipulate data efficiently. This guide provides a comprehensive list of SQL interview questions segmented by experience level—beginner, intermediate, and experienced. For each level, you'll find key questions designed to evaluate the candidate’s proficiency in SQL and their ability to solve data-related problems. The difficulty increases as the experience level rises, and the final section will guide you on how to prepare effectively for these rounds. Beginner (0-2 Years of Experience) At this stage, candidates are expected to know the basics of SQL, common commands, and elementary data manipulation. What is SQL? Explain its importance in data science. Hint: Think about querying, relational databases, and data manipulation. What is the difference between WHERE ...

Spacy errors and their solutions

 Introduction: There are a bunch of errors in spacy, which never makes sense until you get to the depth of it. In this post, we will analyze the attribute error E046 and why it occurs. (1) AttributeError: [E046] Can't retrieve unregistered extension attribute 'tag_name'. Did you forget to call the set_extension method? Let's first understand what the error means on superficial level. There is a tag_name extension in your code. i.e. from a doc object, probably you are calling doc._.tag_name. But spacy suggests to you that probably you forgot to call the set_extension method. So what to do from here? The problem in hand is that your extension is not created where it should have been created. Now in general this means that your pipeline is incorrect at some level.  So how should you solve it? Look into the pipeline of your spacy language object. Chances are that the pipeline component which creates the extension is not included in the pipeline. To check the pipe eleme...

fundamentals of LLM: A story from history of GPTs to the future

Introduction: So there has been a lot of developments in LLM and I have not gone through any of it. In the coming few parts, I will talk about LLM and its related eco-system that has developed and will try to reach to the cutting or more like bleeding edge. Lets go through the main concepts first. What is LLM? LLM[1] refers to large language models; that refer to mainly deep learning based big transformer models that can perform the natural language understanding and natural language generation tasks much better than the previous versions of the models generated in NLP history. LLM models are generally quite big, in terms of 10-100GBs and they can't fit in even in one machine's ram. So, most LLMs are inferenced using bigger GPU cluster systems and are quite computationally exhaustive. What was the first true LLM? The BERTs Transformers were invented on 2017 by vaswani et al in their revolutionary paper called "attention is all you need". After that we had the BER...