How to delete a key from a Python dictionary

Estimated reading time: 2 minutes

This is an addition to the list of questions you may get when in an interview and you are asked to give an overview of Python.

As with how to create an empty dictionary in Python, how to add values to a python dictionary, and how to sort a python dictionary we will take you through the steps here of how to delete a key from a python dictionary.

How to delete a key from a Python dictionary.

How to use the pop() method to delete a key from a dictionary

In the below example we tell Python to find the key “Key1”, then when it does it prints the python dictionary without that key or its value.

empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print(empty_dict1)

#1. Use the pop function
empty_dict1.pop('Key1')
print(empty_dict1)

Result:
{'Key2': '2', 'Key3': '3'}

How to use the Del keyword to delete a key from a dictionary

In this example, we are taking the output of the above example, and just telling the logic to remove the key “Key2” then what it does is it prints the python dictionary without that key or its value.

del empty_dict1["Key2"]
print(empty_dict1)

Result:
{'Key3': '3'}

How to use dict.clear() to delete a key from a dictionary

In this final example, we use dict.clear(). Note this will empty everything out of the dictionary, so be careful in its use.

As can be seen, it takes the output of the previous example and empties it completely.

empty_dict1.clear() # Removes everything from the dictionary.
print(empty_dict1)

Result:
{}

How to sort a Python Dictionary

Estimated reading time: 3 minutes

In our Python Overview Interview Questions we started off the process of trying to prepare you how to answer any questions that may come up in an interview scenario.

We then moved on to show how to discuss Python Dictionary Interview Questions and what may come up.

One of the questions that you may be asked is how to deal with sorting a python dictionary using a key.

Some of the ways that you may want to sort are as follows, read on for code examples:

Python Dictionary Interview Questions

How to use the sorted and Items Method in Python

In the below code, we have created an empty dictionary and then appened in three key-value pairs.

The first print statement just prints out the dictionary in its unordered fashion.

The second print statement does two things:

  1. It, first of all, sorts the empty_dict1 items in order
  2. Then it goes and creates them in a dictionary.

The reason we have to do step two is that the sorted() function returns a sorted list, as a result, it is not in a dictionary format.

empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print("Your unsorted by key dictionary is:",empty_dict1)
print("Your sorted by key dictionary is:",dict(sorted(empty_dict1.items())))

Result:
Your unsorted by key dictionary is: {'Key2': '2', 'Key1': '1', 'Key3': '3'}
Your sorted by key dictionary is: {'Key1': '1', 'Key2': '2', 'Key3': '3'}

How to use List comprehension to sort a dictionary

As a follow on to the above, we could also just iterate over the dictionary using list comprehensions.

The below creates a variable called d. This is set equal to the output of the list comprehension.

Note that inside the {} brackets you have a:b, this purely creates two sets of values that will be used as the output to generate the dictionary.

You will also see that this creates index values, starting at 0, not the actual values we want.

As a result, we just drop these index values and replace them with the values we want using the pop() method.

The final two print statements show the before and after of sorting the dictionary!

d = {a:b for a, b in enumerate(empty_dict1.values())}
print(d)
d["Key2"] = d.pop(0) #replaces 0 with Key2
d["Key1"] = d.pop(1) #replaces 1 with Key1
d["Key3"] = d.pop(2) #replaces 2 with Key3
print(d)
print(dict(sorted(d.items())))

Result:
{0: '2', 1: '1', 2: '3'}
{'Key2': '2', 'Key1': '1', 'Key3': '3'}
{'Key1': '1', 'Key2': '2', 'Key3': '3'}

How To Add Values to a Python Dictionary

Estimated reading time: 1 minute

As part of our ongoing series about Python Interview questions, we discussed how you would create an empty dictionary.

In this posting, we are going to go through the different ways you could add values to your dictionary.

In the below code, we have created an empty dictionary for you.

So as we go down through lines 5 and 6, you can see that we have created two key names and assigned them values. This has the result of populating those key-value pairs to empty_dict1.

Now as you build out your Python logic, you may just want to update the dictionary by using empty_dict1.update(Add key-value pair here).

Finally, there is the option to just use an if statement that checks if the values you want to add exist already, and if not it adds them in.

#How do add values to a python dictionary
empty_dict1 = {}
empty_dict2 = dict()

empty_dict1['Key1'] = '1'
empty_dict1['Key2'] = '2'
print(empty_dict1)

#Example1 - #Appending values to a python dictionary
empty_dict1.update({'key3': '3'})
print(empty_dict1)

#Example2 - Use an if statement
if "key4" not in empty_dict1:
    empty_dict1["key4"] = '4'
else:
    print("Key exists, so not added")
print(empty_dict1)

Output:
{'Key1': '1', 'Key2': '2'}
{'Key1': '1', 'Key2': '2', 'key3': '3'}
{'Key1': '1', 'Key2': '2', 'key3': '3', 'key4': '4'}

How To Create An Empty Dictionary In Python

Estimated reading time: 1 minute

In our recent video Python dictionary interview questions, we discussed a number of topics around Python dictionaries .

Here we will discuss how to create an empty dictionary.

In the below code, you will see there are two ways to create:

  1. Use a variable that is equal to empty curly brackets
  2. Just make an empty variable equal to the dict() function.

Creating empty dictionaries has many benefits as you can manipulate them as they are mutable.

Also, they can grow and shrink as you need, you just need to make sure that any new key you add is unique and not already stored in the dictionary.

Another thing to note about them is that they are unordered.

Finally, if you are adding data to a dictionary, the keys are case-sensitive, so the same key can exist in the dictionary, but it has to be different regards the case applied to it.

# How do you create an empty dictionary?
empty_dict1 = {}
empty_dict2 = dict()
print(empty_dict1)
print(empty_dict2)
print(type(empty_dict1))
print(type(empty_dict2))

Output:
{}
{}
<class 'dict'>
<class 'dict'>

 

Python Dictionary Interview Questions

Estimated reading time: 6 minutes

In our first video on python interview questions we discussed some of the high-level questions you may be asked in an interview.

In this post, we will discuss interview questions about python dictionaries.

So what are Python dictionaries and their properties?

First of all, they are mutable, meaning they can be changed, please read on to see examples.

As a result, you can add or take away key-value pairs as you see fit.

Also, key names can be changed.

One of the other properties that should be noted is that they are case-sensitive, meaning the same key name can exist if it is in different caps.

So how do you create an empty dictionary in Python?

As can be seen below, the process is straightforward, you just declare a variable equal to two curly brackets, and hey presto you are up and running.

An alternative is to declare a variable equal to dict(), and in an instance, you have an empty dictionary.

The below block of code should be a good example of how to do this:

# How do you create an empty dictionary?
empty_dict1 = {}
empty_dict2 = dict()
print(empty_dict1)
print(empty_dict2)
print(type(empty_dict1))
print(type(empty_dict2))

Output:
{}
{}
<class 'dict'>
<class 'dict'>

How do you add values to a Python dictionary?

If you want to add values to your Python dictionary, there are several ways possible, the below code, can help you get a better idea:

#How do add values to a python dictionary
empty_dict1 = {}
empty_dict2 = dict()

empty_dict1['Key1'] = '1'
empty_dict1['Key2'] = '2'
print(empty_dict1)

#Example1 - #Appending values to a python dictionary
empty_dict1.update({'key3': '3'})
print(empty_dict1)

#Example2 - Use an if statement
if "key4" not in empty_dict1:
    empty_dict1["key4"] = '4'
else:
    print("Key exists, so not added")
print(empty_dict1)

Output:
{'Key1': '1', 'Key2': '2'}
{'Key1': '1', 'Key2': '2', 'key3': '3'}
{'Key1': '1', 'Key2': '2', 'key3': '3', 'key4': '4'}

How do you sort a Python dictionary?

One of the properties of dictionaries is that they are unordered, as a result, if it is large finding what you need may take a bit.

Luckily Python has provided the ability to sort as follows:

#How to sort a python dictionary?
empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print("Your unsorted by key dictionary is:",empty_dict1)
print("Your sorted by key dictionary is:",dict(sorted(empty_dict1.items())))

#OR - use list comprehension
d = {a:b for a, b in enumerate(empty_dict1.values())}
print(d)
d["Key2"] = d.pop(0) #replaces 0 with Key2
d["Key1"] = d.pop(1) #replaces 1 with Key1
d["Key3"] = d.pop(2) #replaces 2 with Key3
print(d)
print(dict(sorted(d.items())))

Output:
Your unsorted by key dictionary is: {'Key2': '2', 'Key1': '1', 'Key3': '3'}
Your sorted by key dictionary is: {'Key1': '1', 'Key2': '2', 'Key3': '3'}
{0: '2', 1: '1', 2: '3'}
{'Key2': '2', 'Key1': '1', 'Key3': '3'}
{'Key1': '1', 'Key2': '2', 'Key3': '3'}

How do you delete a key from a Python dictionary?

From time to time certain keys may not be required anymore. In this scenario, you will need to delete them. In doing this you also delete the value associated with the key.

#How do you delete a key from a dictionary?
empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
print(empty_dict1)

#1. Use the pop function
empty_dict1.pop('Key1')
print(empty_dict1)

#2. Use Del

del empty_dict1["Key2"]
print(empty_dict1)

#3. Use dict.clear()
empty_dict1.clear() # Removes everything from the dictionary.
print(empty_dict1)

Output:
{'Key2': '2', 'Key1': '1', 'Key3': '3'}
{'Key2': '2', 'Key3': '3'}
{'Key3': '3'}
{}

How do you delete more than one key from a Python dictionary?

Sometimes you may need to remove multiple keys and their values. Using the above code repeatedly may not be the most efficient way to achieve this.

To help with this Python has provided a number of ways to achieve this as follows:

#How do you delete more than one key from a dictionary
#1. Create a list to lookup against
empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
empty_dict1['Key4'] = '4'
empty_dict1['Key5'] = '5'
empty_dict1['Key6'] = '6'

print(empty_dict1)

dictionary_remove = ["Key5","Key6"] # Lookup list

#1. Use the pop method

for key in dictionary_remove:
  empty_dict1.pop(key)
print(empty_dict1)

#2 Use the del method
dictionary_remove = ["Key3","Key4"]
for key in dictionary_remove:
  del empty_dict1[key]
print(empty_dict1)

How do you change the name of a key in a Python dictionary?

There are going to be scenarios where the key names are not the right names you need, as a result, they will need to be changed.

It should be noted that when changing the key names, the new name should not already exist.

Below are some examples that will show you the different ways this can be acheived.

# How do you change the name of a key in a dictionary
#1. Create a new key , remove the old key, but keep the old key value

# create a dictionary
European_countries = {
    "Ireland": "Dublin",
    "France": "Paris",
    "UK": "London"
}
print(European_countries)
#1. rename key in dictionary
European_countries["United Kingdom"] = European_countries.pop("UK")
# display the dictionary
print(European_countries)

#2. Use zip to change the values

European_countries = {
    "Ireland": "Dublin",
    "France": "Paris",
    "United Kingdom": "London"
}

update_elements=['IRE','FR','UK']

new_dict=dict(zip(update_elements,list(European_countries.values())))

print(new_dict)

Output:
{'Ireland': 'Dublin', 'France': 'Paris', 'UK': 'London'}
{'Ireland': 'Dublin', 'France': 'Paris', 'United Kingdom': 'London'}
{'IRE': 'Dublin', 'FR': 'Paris', 'UK': 'London'}

How do you get the min and max key and values in a Python dictionary?

Finally, you may have a large dictionary and need to see the boundaries and or limits of the values contained within it.

In the below code, some examples of what you can talk through should help explain your knowledge.

#How do you get the min and max keys and values in a dictionary?
dict_values = {"First": 1,"Second": 2,"Third": 3}

#1. Get the minimum value and its associated key
minimum = min(dict_values.values())
print("The minimum value is:",minimum)
minimum_key = min(dict_values.items())
print(minimum_key)

#2. Get the maximum value and its associated key
maximum = max(dict_values.values())
print("The maximum value is:",maximum)
maximum_key = max(dict_values.items())
print(maximum_key)

#3. Get the min and the max key
minimum = min(dict_values.keys())
print("The minimum key is:",minimum)

#2. Get the maximum value and its associated key
maximum = max(dict_values.keys())
print("The maximum key is:",maximum)

Output:
The minimum value is: 1
('First', 1)
The maximum value is: 3
('Third', 3)
The minimum key is: First
The maximum key is: Third

How To Check For Unwanted Characters Using Loops With Python

Estimated reading time: 3 minutes

On this website, we have posted about how to remove unwanted characters from your data and How to remove characters from an imported CSV file both will show you different approaches.

In this blog posting, we are going to approach the process by using loops within a function. Essentially we are going to pass a list and then we are going to loop through the strings to check the data against it.

Step 1 – Import the data and create a data frame

The first bit of work we need to complete is to load the data. Here we create a dictionary with their respective key-value pairs.

In order to prepare the data to be processed through the function in step 2, we then load it into a data frame.

import pandas as pd
#Create a dataset locally
data = {'Number':  ["00&00$000", '111$11111','2222€2222','3333333*33','444444444£','555/55555','666666@666666'],
        'Error' : ['0','0','0','0','0','0','0']}

#Create a dataframe and tell it where to get its values from
df = pd.DataFrame (data, columns = ['Number','Error'])

Step 2 – Create the function that checks for invalid data

This is the main piece of logic that gives the output. As you can see there is a list “L” that is fed to the function run.

One thing to note is that *l is passed to the function, as there is more than one value in the list, otherwise the program would not execute properly.

To start off we create a data frame, which extracts using a regular expression the characters we don’t want to have.

Next, we then need to drop a column that is generated with NAN values, as these are not required.

Then we updated the original data fame with the values that we found.

Just in case if there are any NAN values in this updated column “Error”, we remove them on the next line.

The main next is the loop that creates a new column called “Fix”. This holds the values that will be populated into the fix after the data we don’t want is removed and is data cleansed.

The data we do not need is in str.replace.

#Function to loop through the dataset and see if any of the list values below are found and replace them
def run(*l):
    #This line extracts all the special characters into a new column
    #Using regular expressions it finds values that should not appear
    df2 = df['Number'].str.extract('(\D+|^(0)$)') # New dataframe to get extraction we need
    print(df2)
    df2 = df2.drop(1, axis=1) # Drops the column with NAN in it, not required

    df['Error'] = df2[0] # Updates original dataframe with values that need to be removed.
    #This line removes anything with a null value
    df.dropna(subset=['Error'], inplace=True)
    #This line reads in the list and assigns it a value i, to each element of the list.
    #Each i value assigned also assigns an index number to the list value.
    #The index value is then used to check whether the value associated with it is in the df['Number'] column 
    #and then replaces if found
    for i in l:
        df['Fix']= df['Number'].str.replace(i[0],"").str.replace(i[1],"").str.replace(i[2],"").str.replace(i[3],"") \
        .str.replace(i[4],"").str.replace(i[5],"").str.replace(i[6],"")
        print("Error list to check against")
        print(i[0])
        print(i[1])
        print(i[2])
        print(i[3])
        print(i[4])
        print(i[5])
        print(i[6])
    print(df)

#This is the list of errors you want to check for
l = ['$','*','€','&','£','/','@']

Step 3 – Run the program

To run this program, we just execute the below code. All this does is read in the list “L” to the function “run” and then the output in step 4 is produced

run(l)

Step 4 – Output

Error list to check against
$
*
€
&
£
/
@
          Number Error           Fix
0      00&00$000     &       0000000
1      111$11111     $      11111111
2      2222€2222     €      22222222
3     3333333*33     *     333333333
4     444444444£     £     444444444
5      555/55555     /      55555555
6  666666@666666     @  666666666666

Process finished with exit code 0

How To Fix TypeError: unhashable type ‘slice’

Estimated reading time: 2 minutes

So you have a Python dictionary, and you want to retrieve data from it and print it to a screen. There are some characteristics of Python that first of all should be understood:

  1. They are mutable
  2. They also have the ability to grow and shrink as required.
  3. Data is accessed within the dictionary via keys.

The last point is very important as dictionaries do not have an index value, and this is why you get the TypeError you are here to solve for.

So let us recreate the problem

In the below code we have a dictionary called “userdata”, with its key-value pairs.

The loop is trying to retrieve the index value 1 for all the values in dai_data.

As can be seen, dai_data is trying to retrieve the last three index values within the dictionary.

As noted above the only way to access dictionary values is through their key values.

userdata = {
	  "name": "Data Analytics Ireland",
	  "Country": "Ireland",
	  "City": "Dublin",
	  "Age": "1000 years!",
}

dai_data = userdata[:3]

for i in dai_data:
	     print(i[1])

Output:
Traceback (most recent call last):
  File "", line 8, in <module>
    dai_data = userdata[:3]
TypeError: unhashable type: 'slice'

So how do we fix this problem?

First of all, values are accessed through the key within the dictionary

In the below dictionary the key values are: Name, Country, City, Age

userdata = {
	  "Name": "Data Analytics Ireland",
	  "Country": "Ireland",
	  "City": "Dublin",
	  "Age": "1000 years!",
}

print(userdata["Name"])
print(userdata["Country"])
print(userdata["City"])
print(userdata["Age"])

Output:
Data Analytics Ireland
Ireland
Dublin
1000 years!

As a result, now we are able to access the values associated with each key.

Did you know you could add a list to one of your key-value pairs?

In the above example, we focused on a single value, but we could also make a key equal to a list.

userdata = {
	  "Name": ["Joe","Jim"],
	  "Country": "Ireland",
	  "City": ["Dublin","Cork","Limerick"],
	  "Age": "1000 years!"
}

print(userdata["Name"])
print(userdata["Country"])
print(userdata["City"])
print(userdata["Age"])

Output:
['Joe', 'Jim']
Ireland
['Dublin', 'Cork', 'Limerick']
1000 years!

how do I merge two dictionaries in Python?

Python dictionaries which are used in data analytics frequently and by their nature are enclosed in {} and have key:value pairs, so the data in them can be retrieved easily.

There maybe a scenario where you need to merge two dictionaries, but how would you acheive this?

The good thing is that Python dictionaries are unordered and mutable, meaning that what makes them up can be changed.

Lets start off by creating two dictionaries

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"D":"4", "E":"5", "F":"6"}
print("dictionary 1 is:", dict1)
print("dictionary 2 is:", dict2)
print(type(dict1))
print(type(dict2))

Its output is as follows:
dictionary 1 is: {'A': '1', 'B': '2', 'C': '3'}
dictionary 2 is: {'D': '4', 'E': '5', 'F': '6'}
<class 'dict'>
<class 'dict'>

So the objective is to get these two dictionaries into one, how is this achieved?

Approach 1 – Use PEP 448

This approach uses PEP 448 which allows * iterable unpacking operator and ** dictionary unpacking operators to be implemented.

As can be seen below , it is a quick and efficient way to quickly merge, without impacting the two dictionaries structure.

dict3 = {**dict1, **dict2}
print(dict3)
print(type(3))

With output:
{'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'}
<class 'int'>

Approach 2 – Update when some values not required.

You maybe faced with a situation where you only want certain values from the second dictionary.

In the below there are common keys to both dictionares, namely “A” and “B”.

What the update is doing is it keeps all the values of dictionary 1, and adds in any key value pair that is not A or B.

This scenario could be encountered where dict1 is the master dictionary and always correct, and just needs new values added that do not exist already.

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"A":"2", "E":"5", "B":"6"}
dict2.update((dict1))
print(dict2)
print(type(dict2))

Resulting in:
{'A': '1', 'E': '5', 'B': '2', 'C': '3'}
<class 'dict'>

Approach 3 – Iterating over the dictionaries

In this scenario, there are a few things going on, that should be explained.

dict1.copy ===> This is done so that you have the original, as it maybe updated if there where duplicate keys.

The loop then just goes through dict2 key value pairs, and adds the key value pairs to dict3, which was originally dict1.

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"D":"4", "E":"5", "F":"6"}

dict3 = dict1.copy()

for key,value in dict2.items():
    dict3[key] = value
print(dict3)

Which gives you:
{'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'}
<class 'dict'>

Summing it all up

In conclusion, depending on what way you would like to approach, we have outlined options.

Probably the most important thing that came out of this, is that dictionaries can be changed, as a result when applying some of the

techniques above, before proceeding be sure to check if you want to keep the original values.