How To Create An Empty Dictionary In Python


Estimated reading time: 2 minutes

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.
  3. Use the key/values in a list.
  4. Use a function
  5. Use List comprehension

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))

#Use Keys,values in lists
# list_keys = []
# List_values = []
#
# n = dict(zip(list_keys, List_values))
# print(n)
# print(type(n))

# Note using Zip just allows you to iterate over two lists in parallel  , and the output is a set of pairs


##Use a function ##
#
# def create_dictionary():
#     d = {}
#     print(d)
#     print(type(d))
#
# create_dictionary()


##Use list comprehension##
# loop_list = []
# d = { i: j for i, j in enumerate(loop_list)}
# print(d)
# print(type(d))

 

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'}

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 use a loop to sort a Python dictionary

d={0:2, 1: 1, 2: 3}
dict_loop={}
for i in sorted(d):
   dict_loop[i]=d[i]
print("")
print("Sorted dictionary using a loop",dict_loop)

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 Delete a Set of Keys From a Python Dictionary


Estimated reading time: 2 minutes

In our last video on how to delete a key from a python dictionary, we illustrated where one key could be removed easily.

But what if you wanted to remove one or more keys?

How to delete more than one key from a Python dictionary

In the below code, we have created an empty dictionary. This will be populated by values in “dictionary_remove”.

Option1 uses the pop method :

  1. It creates an empty dictionary and then populates it with keys and values.
  2. Then it uses a loop to iterate over the list dictionary_remove.
  3. Then it looks at those and uses the pop method to find those values in the empty_dict1, and removes them

As a result, the following is what is returned:

Before:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’, ‘Key5’: ‘5’, ‘Key6’: ‘6’}

After:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’}

Option 2 uses the Del method :

In this second scenario, we do the following steps:

  1. We populate the dictionary_remove with two values, that are from the result of scenario 1 above.
  2. Then it uses a loop to iterate over the list dictionary_remove.
  3. Then it looks at those and uses the del method to find those values in the empty_dict1, and removes them

As a result, the following is what is returned:

Before:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’}

After:

{‘Key2’: ‘2’, ‘Key1’: ‘1’}

Slide 8
#How to 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)

We hope you enjoyed this, we have plenty of videos that you can look at to improve your knowledge of Python here: Data Analytics Ireland Youtube

Click here if you want to know how would you change the name of a key in a python dictionary as an alternative!

How Would You Change The Name Of a Key in a Python Dictionary


In our last example of working with dictionaries, we showed you How To Delete a Set of Keys From a Python Dictionary. This is a very useful scenario if you want to tidy up the dictionary and remove data not required.

Following on from that, in this post, we are going to look at changing key names. You may find that you have the dictionary you want but you need to change some of the key names to ensure the proper names are consistent with other parts of your program.

How would you change the name of a key in a Python dictionary

Option1 uses the pop method :

  1. Create a dictionary with the key-value pairs in it. Note that this will also be used for the second option.
  2. Then this line European_countries[“United Kingdom”] = European_countries.pop(“UK”) basically says to find “UK” in the values, drop it and replace it with the value “United Kingdom”

Before the values using the pop method where:

{‘Ireland’: ‘Dublin’, ‘France’: ‘Paris’, ‘UK’: ‘London’}

After the values using the pop method are:
{‘Ireland’: ‘Dublin’, ‘France’: ‘Paris’, ‘United Kingdom’: ‘London’}

Option 2 uses the zip method :

  1. In this scenario, we have created a dictionary called European countries.
  2. the objective here is to replace the names with the three-letter country code.
  3. Note it updates the values into new_dict using zip, and using the update_elements list, based on the order they are in, in both.

Before the values using the zip method where:

{‘Ireland’: ‘Dublin’, ‘France’: ‘Paris’, ‘United Kingdom’: ‘London’}

After the values using the zip method are:
{‘IRE’: ‘Dublin’, ‘FR’: ‘Paris’, ‘UK’: ‘London’}

#Slide 9
# 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)

We hope you enjoyed this, we have plenty of videos that you can look at to improve your knowledge of Python here: Data Analytics Ireland Youtube