Python Dictionary Of Lists


A Python dictionary of lists refers to a dictionary that consists of lists as values.

For instance, if

dict1 = {'A': [1, 2, 3], 'B':[2, 5]}

dict1 is a dictionary of lists, with the following key:value pairs:

'A':[1, 2, 3]
'B':[2, 5]

The values of the dictionary are lists – [1, 2, 3] and [2, 5] – while the keys are strings ('A' and 'B').

In today’s post, we’ll learn to create and modify dictionary of lists. We’ll also talk about the relationship between a dictionary of lists and a dataframe. Last but not least, we’ll work on a practice question that stores user input as a Python dictionary of lists.

How to create a Python Dictionary with List As Value

First, let’s discuss three different ways to create a Python dictionary of lists.

  • Method 1: Create and initialize a dictionary using {} or dict()
  • Method 2: Create an empty dictionary and add key:value pairs to it
  • Method 3: Use the built-in zip() function in Python

Method 1: Create and initialize a dictionary using {} or dict()

The most direct way to create a Python dictionary of lists is to create and initialize the dictionary directly.

dict1 = {'A':[11, '2', 53], 'B':[4, 50]}
dict2 = dict(X=[5, 7, 9], Y = [41, 15])
dict3 = dict([(1, [6, 5, 8]), (4, [9, 1, 2])])

print(dict1)
print(dict2)
print(dict3)

In the code above, we first use {} to declare and initialize dict1 with the following key:value pairs

'A':[11, '2', 53]
'B':[4, 50]

Next, we use the dict() method to create another dictionary called dict2, with the following key:value pairs

'X':[5, 7, 9]
'Y':[41, 15]

Finally, we use the dict() method to create a dictionary called dict3, with the following key:value pairs

1:[6, 5, 8]
4:[9, 1, 2]

In each of the examples above, the values of the dictionaries are lists. If you run the code above, you’ll get the following output:

{'A': [11, '2', 53], 'B': [4, 50]}
{'X': [5, 7, 9], 'Y': [41, 15]}
{1: [6, 5, 8], 4: [9, 1, 2]}

Method 2: Create an empty dictionary and add key:value pairs to it

Besides declaring and initializing a dictionary directly, we can create an empty dictionary and add key:value pairs to it subsequently:

dict1 = {}
dict2 = dict()

dict1['A'] = [1, 2, 3]
dict1['B'] = [10, 12]

dict2[5] = [78, 9, 2]
dict2[4] = [1, 7]

print(dict1)
print(dict2)

In the code above, we first declare two empty lists – dict1 and dict2.

Next, we add the following key:value pairs to dict1 on lines 4 and 5:

'A':[1, 2, 3]
'B':[10, 12]

On lines 7 and 8, we add the following pairs to dict2:

5:[78, 9, 2]
4:[1, 7]

If you run the code above, you’ll get the following output:

{'A': [1, 2, 3], 'B': [10, 12]}
{5: [78, 9, 2], 4: [1, 7]}

Method 3: Use the built-in zip() function in Python

Last but not least, another convenient way to create a dictionary of lists is to use a Python built-in function called zip().

This function can be used to ‘zip’ two lists together into a iterator of tuples. This iterator can then be converted to a dictionary using the dict() method.

Let’s look at an example:

keysList = ['A', 'B', 'C']
valuesList = [[7, 1, 5], [17, 9, 18], [11, 1]]

dict1 = dict(zip(keysList, valuesList))

print(dict1)

Here, we first declare a list called keysList on line 1. This list contains the keys that we want to use in our dictionary.

Next, we declare a list called valuesList, which contains the values that we want to use in our dictionary.

On line 4, we use the zip() function to zip keysList and valuesList together. This returns an iterator of tuples, which can be converted to a dictionary using the dict() method.

Finally, on line 6, we print the value of dict1.

If you run the code above, you’ll get the following output:

{'A': [7, 1, 5], 'B': [17, 9, 18], 'C': [11, 1]}

The keys for the resulting dictionary come from keysValue while the values come from valuesList.

How to access items in a Python Dictionary of Lists

Now that we know how to create a dictionary of lists, let’s discuss how we can access any item in the dictionary.

To do that, we use its key. This gives us the value of that item, which is a list.

To access the items inside that list, we use its index.

An example is shown below:

dict1 = {'X':[1, 2, 3], 'Y':[4, 5, 6]}

print(dict1['X'])

print(dict1['X'][0])

Here, we first use dict1['X] to access the first list in the dictionary. Next, we use dict1['X][0] to access the first item in dict1['X'].

If you run the code above, you’ll get the following output:

[1, 2, 3]
1

How to modify items in a Python Dictionary of Lists

To update an item in a Python dictionary of lists, we can assign a new list to its value, as shown in the example below:

dict1 = {'X':[1, 2, 3], 'Y':[4, 5, 6]}

dict1['X'] = [7, 8, 9, 10]

print(dict1)

If you run the code above, you’ll get the following output:

{'X': [7, 8, 9, 10], 'Y': [4, 5, 6]}

We can also update an item in a Python dictionary of lists using the append() method:

dict1 = {'X':[1, 2, 3], 'Y':[4, 5, 6]}

dict1['X'].append(12)

print(dict1)

The code above appends 12 to dict1['X'].

If you run the code above, you’ll get the following output:

{'X': [1, 2, 3, 12], 'Y': [4, 5, 6]}

Converting a Python Dictionary of Lists to a Dataframe

Python dictionary of lists are very useful in data science. A common library used for data analysis is the Pandas library, which uses a special datatype known as a Pandas dataframe.

A dataframe can be created from a Python dictionary of lists, where the keys in the dictionary serve as a column heading and the values (i.e. the lists) are the column values.

For instance, the screenshot below shows how a Python dictionary of lists (dict1) can be converted to a Pandas dataframe (using the Dataframe() method).

Python dictionary of lists to dataframe

As you can see, each key in the dictionary (i.e. 'Name', 'Age' and 'Level') corresponds to a column heading in the dataframe, while the lists become the column values.

If you are interested in what a Pandas dataframe is used for, you can refer to this post for more information on using dataframes in Python.

Practice Question

Now that we are familiar with Python dictionary of lists, let’s move on to the practice question for today.

For today’s practice question, you need to write a function called getMarks().

Inside the function, you should do the following tasks repeatedly until the user enters '-1' to quit:

  1. Prompt the user to enter class name or -1 to quit
  2. Prompt the user to enter class marks, separated by a comma
  3. Store the class name (as a string) and marks (as a list of integers) entered by the user into a Python dictionary of lists, where the key is the class name and the value is the marks.

As long as the user does not enter '-1', repeat task 1 to 3 above. If the user enters '-1', return the dictionary of list.

You can assume that the user always enters integers when prompted to enter class marks.

Expected Results

Here’s an example showing what the function should do. If you run the code below

marksDict = getMarks()

print(marksDict)

the function should behave as follows:

Enter Class Name or -1 to Quit: 2A
Enter Marks, Separated by Commas: 23, 31, 41, 58
Enter Class Name or -1 to Quit: 2B
Enter Marks, Separated by Commas: 76, 49, 31, 72
Enter Class Name or -1 to Quit: 2C
Enter Marks, Separated by Commas: 17, 31, 90, 25
Enter Class Name or -1 to Quit: -1
{'2A': [23, 31, 41, 58], '2B': [76, 49, 31, 72], '2C': [17, 31, 90, 25]}

Suggested Solution

def getMarks():

    result = {}

    while True:

        className = input('Enter Class Name or -1 to Quit: ')

        if className == '-1':
            break
        
        marks = input('Enter Marks, Separated by Commas: ')

        result[className] = list(map(int, marks.split(',')))

    return result

In the suggested solution above, we first define a function called getMarks() on line 1.

Inside the function, we declare an empty dictionary called result.

Next, we use a while True loop to repeatedly prompt users for input. On line 7, we prompt users to enter the class name or -1 to quit.

If the user enters -1, we use the break statement on line 10 to exit the while loop.

Else, we proceed to line 12 where we prompt users to enter the class marks, and assign the input (which is a string) to a variable called marks.

Next, on line 14, we do a number of things.

First, we use marks to call the split() method for strings. This method splits a string into a list, using the argument as a delimiter. In our code above, we pass ',' as the delimiter. Suppose marks = '1, 2, 3, 4', the split() method splits the string into the list ['1', ' 2', ' 3', ' 4'].

Next, we pass this list and the int() function to another function called map().

The map() function is a built-in function in Python that applies a function to all the elements of an iterable (such as a list). In our suggested solution above, we use the map() function to apply the int() function to all the elements in marks.split(',').

Suppose marks.split(',') returns the list ['1', ' 2', ' 3', ' 4']. The map() function then applies the int() function to all the elements in this list to convert them to integers. This gives us a map object that can be converted to a list using the list() function.

After converting, we get the list [1, 2, 3, 4], which we  assign to result[className].

This adds a key:value pair to the result dictionary.

Finally, outside the while loop, we return the value of result on line 16.

With that, the function is complete.

Written by Jamie | Last Updated December 12, 2020

Recent Posts