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'

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

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

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

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

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

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

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

{'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())}
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

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'

#1. Use the pop function

#2. Use Del

del empty_dict1["Key2"]

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

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


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

#1. Use the pop method

for key in dictionary_remove:

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

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"
#1. rename key in dictionary
European_countries["United Kingdom"] = European_countries.pop("UK")
# display the dictionary

#2. Use zip to change the values

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




{'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())

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

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

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

Python Overview Interview Questions

Estimated reading time: 4 minutes

So you have landed an interview and worked hard at upskilling your Python knowledge. There are going to be some questions about Python and the different aspects of it that you will need to be able to talk about that are not all coding!

Here we discuss some of the key elements that you should be comfortable explaining.

What are the key Features of Python?

In the below screenshot that will feature in our video, if you are asked this question they will help you be able to discuss.

Below I have outlined some of the key benefits you should be comfortable discussing.

It is great as it is open source and well-supported, you will always find an answer to your question somewhere.

Also as it is easy to code and understand, the ability to quickly upskill and deliver some good programs is a massive benefit.

As there are a lot of different platforms out there, it has been adapted to easily work on any with little effort. This is a massive boost to have it used across a number of development environments without too much tweaking.

Finally, some languages need you to compile the application first, Python does not it just runs.

What are the limitations of Python?

While there is a lot of chat about Python, it also comes with some caveats which you should be able to talk to.

One of the first things to discuss is that its speed can inhibit how well an application performs. If you require real-time data and using Python you need to consider how well performance will be inhibited by it.

There are scenarios where an application is written in an older version of code, and you want to introduce new functionality, with a newer version. This could lead to problems of the code not working that currently exists, that needs to be rewritten. As a result, additional programming time may need to be factored in to fix the compatibility issues found.

Finally, As Python uses a lot of memory you need to have it on a computer and or server that can handle the memory requests. This is especially important where the application is been used in real-time and needs to deliver output pretty quickly to the user interface.

What is Python good for?

As detailed below, there are many uses of Python, this is not an exhaustive list I may add.

A common theme for some of the points below is that Python can process data and provide information that you are not aware of which can aid decision-making.

Alternatively, it can also be used as a tool for automating and or predicting the behaviour of the subjects it pertains to, sometimes these may not be obvious, but helps speed up the delivery of certain repetitive tasks.

What are the data types Python support?

Finally below is a list of the data types you should be familiar with, and be able to discuss. Some of these are frequently used.

These come from the Python data types web page itself, so a good reference point if you need to further understand or improve your knowledge.

ValueError: Columns must be same length as key

Estimated reading time: 3 minutes

Are you looking to learn python , and in the process coming across this error and trying to understand why it occurs?

In essence, this usually occurs when you have more than one data frames and in the process of writing your program you are trying to use the data frames and their data, but there is a mismatch in the no of items in each that the program cannot process until it is fixed.

A common scenario where this may happen is when you are joining data frames or splitting out data, these will be demonstrated below.

Scenario 1 – Joining data frames

Where we have df1[[‘a’]] = df2 we are assigning the values on the left side of the equals sign to what is on the right.

When we look at the right-hand side it has three columns, the left-hand side has one.

As a result the error “ValueError: Columns must be same length as key” will appear, as per the below.

import pandas as pd

list1 = [1,2,3]
list2 = [[4,5,6],[7,8,9]]

df1 = pd.DataFrame(list1,columns=['column1'])
df2 = pd.DataFrame(list2,columns=['column2','column3','column4'])

df1[['a']] = df2

The above code throws the below error:

The objective here is to have all the columns from the right-hand side, beside the columns from the left-hand side as follows:

What we have done is make both sides equal regards the no of columns to be shown from df2
Essentially we are taking the column from DF1, and then bringing in the three columns from DF2.
The columna, columnb, columnc below correspond to the three columns in DF2, and will store the data from them.

The fix for this issue is : df1[[‘columna’,’columnb’,’columnc’]] = df2

print (df1)

Scenario 2 – Splitting out data

There may be an occasion where you have a python list, and you need to split out the values of that list into separate columns.

new_list1 = ['1 2 3']
df1_newlist = pd.DataFrame(new_list1,columns=['column1'])

In the above, we have created a list, with three values that are part of one string. Here what we are looking to do is create a new column with the below code:

df1_newlist[["column1"]] = df1_newlist["column1"].str.split(" ", expand=True) #Splitting based on the space between the values.


When we run the above it throws the following valueerror:

The reason it throws the error is that the logic has three values to be split out into three columns, but we have only defined one column in df1_newlist[[“column1”]]

To fix this, we run the below code:

df1_newlist[["column1","column2","column3"]] = df1_newlist["column1"].str.split(" ", expand=True) #Splitting based on the space between the values.


This returns the following output, with the problem fixed!

How to Pass Python Variables to Javascript

Estimated reading time: 4 minutes

In our recent blog posting How to Pass a Javascript Variable to Python using JSON, we demonstrated how to easily use AJAX to pass whatever data you wanted and then manipulate it with Python.

In this blog posting, we are going to show how to do this the other way around. The scenario is that you have an application and or website that wants to use data generated through Python, but let Javascript then use it within the application.

As Python can be connected to numerous databases and files ( txt, excel) etc, this piece of logic is very useful for the programmer looking to integrate both programming languages.

Let’s start looking at the code, and see how this can be achieved.

Step 1 – What Files are generated?

This program uses Python Flask to create a web page, that has a drop-down menu. The two files used to generate this are as follows:

(A) – This is the python file that creates a website and loads a template HTML file as outlined below.

(B) Index.html – This is the template file that loads into the browser and runs all the javascript. The javascript loaded here also loads the python data passed over from

Step 2 – APP.PY code overview

The Python library that enables webpage creation is called Flask, and as can be seen below it has to be imported.

In addition, we need to also import render_template which tells the program to go to the templates folder and load “Index.HTML”

The variable that is been passed to JavaScript is called name, and these are the values that you will see in the web browser when it is loaded.

from flask import Flask, render_template

app = Flask(__name__)

def index():
    name = ['Joe','John','Jim','Paul','Niall','Tom']
    return render_template('index.html', name=name)

if __name__ == "__main__":

Step 3 – Index.HTML overview

Here is the template HTML file that runs in the browser. You can add CSS etc to this to make it look nicer and more user friendly.

As you can see it has the usual HTML tags appear as part of a website.

Well look at some of the code further:

In this bit <select id =’select’> </select>, this is the dropdown menu that will appear when Index.html is opened. It will store all the values passed from python. Note that its id is “select”, this will be used later on.

The main parts to focus on next is between <script></script>. This is what reads in the python data and populates it to the dropdown menu.

In step 2 we mentioned that there was a variable called “name”, with values to be passed over.

This is acheived on this line:

var select = document.getElementById(“select”), test = {{ name | tojson }};

Notice that name appears here, and this is referencing back to the exact same value that was discussed in step 2.

For the rest of the lines, I have explained with comments what each does.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Pass Python variable to Javascript</title>

<select id ='selectvalue'>
    //name = ['Joe','John','Jim','Paul','Niall','Tom']

    var selectvalue = document.getElementById("selectvalue"), test = {{ name | tojson }};
    //The increment operator (++) increments (adds one to) its operand and returns a value.
    for(var i = 0; i < test.length; i++) // This line checks for the length of the data you feeding in i.e the no of items
var selection = document.createElement("OPTION"), // This line creates a variable to store the different values fed in from the JSON object "TEST"
txt = document.createTextNode(test[i]); // This just reads each value from the test JSON variable above
selection.appendChild(txt); // This line appends each value as it is read.
selection.setAttribute("value",test[i]); // This line sets each value read in as a value for the drop down
selectvalue.insertBefore(selection,selectvalue.lastChild); //This reads eah value into the dropdown based on the order in the "TEST" above.

Step 4 – What the output looks like!

From step 2, these are values we asked to be used in Javascript to populate a dropdown:

name = [‘Joe’,’John’,’Jim’,’Paul’,’Niall’,’Tom’]

Python variable passed to Javascript

What Is An Array In Python?

Estimated reading time: 3 minutes

Python arrays are used to manage how data is analysed and have the data in a structured form for the data analyst or data scientist to use.

What is an Array?

An array has the following properties:

  1. The data in it is of the same data type.
  2. The data is stored as contiguous memory locations, meaning the lowest value is at index 0 and the last value is at the highest index value.
  3. Arrays assign index values to each data point contained within it.
  4. You can append values to the array.
  5. You can delete values from the array, that is it is mutable.

What are the differences between arrays and lists?

For the most part arrays and lists are the same, but with one difference:

A list can store any data type you want e.g. strings, integers etc.

On the other hand, arrays can only store data that is of the same data type.

What are the different ways that I can create an array?

(A) Use Numpy

# Use numpy

import numpy as np

a = np.array([1,2,3,4])


[1 2 3 4]
<class 'numpy.ndarray'>

If we have one of the values as a string, all the other values are converted to a string , as follows:
# Use numpy

import numpy as np

a = np.array([1,2,3,'4'])



['1' '2' '3' '4']
<class 'numpy.ndarray'>

# <U11 - When this happens, it means one of the values was returning as a string
# All the other values in the array as a result are converted to strings

(B) Use array

import array as test_array

a = test_array.array('i',[1,2,3])


array('i', [1, 2, 3])
<class 'array.array'>

On the website, below are the list of values that can be populated into the above program, depending on what your need is:

When should I use arrays?

It really depends on the nature of your python program, but below are some examples that may help you make a decision:

(A) Many variables of the same type : There maybe a scenario where you have to create an array to store data that is of the same data type. For example you have a list of codes to look up against, which are all integers.

(B) Faster and more efficient : If speed is what you are looking for using arrays, will help improve performance of your computer program, using lists is much slower.

(C) Compactability and efficiency : If the nature of your program needs to store large amounts of data that needs to be accessed quickly , then this would be a good reason to use them.

(D) Ability to retrieve data quickly through indexing: As arrays have index values associated with them, they data can be easiy retrieved.

(E) Need to compute some mathematical values: Arrays are excellent for any numerical operations you need to complete, as the level of coding is minimal.

import array as test_array

a = test_array.array('i',[1,2,3])

mydivider = 2

mynewlist = [x / mydivider for x in a]

[0.5, 1.0, 1.5]

So in summary:

Speed , efficiency and ease of use are the main reasons to use an array.

We use arrays here in how to show percentage differences between files in python , why not go over and see it in action!

How to Create an XML file from Excel using Python

Estimated reading time: 3 minutes

Are you working on a data analytics project where you need to feed your data to a location that is able to process an XML file?

The ability to get your data into a structured format like XML has many benefits:

(A) You can transfer the data to a web service for processing.

(B) Multiple different formats of your raw data can be standardised, enabling quick conversion and processing.

(C) XML files can be read by multiple different programs, as long as you deliver them in the correct format.

(D) The receiver of data can easily read the XML file and store it on their database.

The ability to use this method to read and transfer data is a very powerful way to help a data analyst process large data sets.

In fact, if you are using cloud-based applications to analyse the information you are storing, this will quickly enable you to deliver the data.

What packages do I need in Python?

The first step is to import the following:

import pandas as pd
from lxml import etree as et

Next we want to read in the source data

In this instance, we are reading an excel file

raw_data = pd.read_excel(r'Link to where your data is stored including the full file name')

Now we want to start building the XML structure

The FIRST STEP is to define the root

root = et.Element('root')

The root is the parent of all the data items (tags) contained in the XML file and is needed as part of the structure

The SECOND STEP is to define the tag names that will store each row of the source data

for row in raw_data.iterrows(): ==> This is a loop that takes runs through each record and populates for each tag.
    root_tags = et.SubElement(root, 'ExportData') #=== > Root name
# These are the tag names for each row (SECTION 1)
    Column_heading_1 = et.SubElement(root_tags, 'Name')
    Column_heading_2 = et.SubElement(root_tags, 'Area')
    Column_heading_3 = et.SubElement(root_tags, 'NoPurchases')
    Column_heading_4 = et.SubElement(root_tags, 'Active')

###These are the values that will be populated for each row above
# The values inside the [] are the raw file column headings.(SECTION 2)
    Column_heading_1.text = str(row[1]['Name'])
    Column_heading_2.text = str(row[1]['Area'])
    Column_heading_3.text = str(row[1]['No Purchases'])
    Column_heading_4.text = str(row[1]['Active'])

The raw file looks like this:

NameAreaNo PurchasesActive
Raw file data that will be imported into the XML file

The THIRD STEP is to create the XML file and populate it with the data from the source file

# This Section outputs the data to an xml file
# Unless you tell it otherwise it saves it to the same folder as the script.
tree = et.ElementTree(root) ==> The variable tree is to hold all the values of "root"
et.indent(tree, space="\t", level=0) ===> This just formats in a way that the XML is readable
tree.write('output.xml', encoding="utf-8") ==> The data is saved to an XML file

The XML output should look like the below


Additional XML data can be added

  1. Add more rows – All you need to do is add onto the source file and save. When you rerun the logic it will read in the extra information.
  2. Add more columns – All you need to do is go to the second step above add in a tag name to SECTION 1. Seperately you will need to add an additional column with data to the source file, and then add that column name to SECTION 2 as well

Python Tutorial: Pandas groupby columns ( video 2)

Pandas groupby using column values

In this second video how to groupby using pandas and as part of expanding the data analytics information of this website, we are looking to explain how you can use a groupby selection but only using the column values and not the column names.

Below we import our data into a dataframe, and then group as follows:

  • Aggregate function
  • Using the cut function and assigning values to bins.
  • Assigning labels to the data frame output based on the bin values.

Why would you want to use Pandas groupby and column values?

This video looks to help understand why going by values might be easier than column names:

  • Column names can change from project to project, using by values allows easy implementation of getting the output regardless of the names used.
  • You could apply this to any Python class, and as long as you can inherit will allow the code to run smoothly.
  • Implementing by value allows a clear understanding of the desired output as the values are clearly understood to generate what is required.
  • You need to understand how data within your data set falls within a particular cohort:
    • This use of values in different programs just needs to change, the underlying logic remains the same.
    • Using column names still means that to group them, the logic still needs to be written.

Python tutorial: Pandas groupby ( Video 1)

In this first video about pandas groupby and as part of expanding the data analytics information of this website, we are looking to explain how you can use a groupby selection to sort your data into similar datasets better so they can be better analysed. In the video below, we import our data into a dataframe, and then group as follows:

  • Directly naming the column
  • Through get_group
  • Using a loop
  • Utilising a lambda function



Python tutorial: Create an input box in Tkinter

Using an tkinter input box for your data projects

There may be an occasion as you are building out a data science or data analytics project, checks need to be performed on the dataset as follows:

  •  Big data sets and speed requirements in conjunction with
  • The need to reduce the volume of data returned which is impeding performance

and this is where input boxes and Tkinter can help!

In the below video, we are demonstrating an introduction to using an input box and validating the input.

We demonstrate how to validate the data entered into the tkinter input box and return a message, this will ensure the user gets the correct data.

Types of uses for a tkinter input box are varied, here are some thoughts:

  • Use an input box to return a set of data for a particular day.
  • Using them to filter down the results to a particular cohort of data.
  • Conduct a string search to find data quality issues to be fixed.