Home ยป How to create a Python Dictionary of Array lists.

Python dictionary of lists

How to create a Python Dictionary of Array lists.

A key value pair data structure with multiple values per key

Let’s say you want to create a list of all your friends and the books they have read. You need to be able to access this by their name and then print the list of books.

What you need is a key value pair structure, but in this case there are multiple values for the key, but the key still needs to be unquie .

We want a structure like this:

PersonValue1Value2Value3Valuen
Jane978123456789097811111111119784444444444
Fred97812346646669781237878788
Max9781234567890
Sally978123456789097812399779799781234545454978123456455
An example table with a key and multiple values

What does a multi-dimensional dictionary look like in Python?

In Python this is easily implemented as a Python Dictionary which looks like this:

KeyValue
Jane[9781234567890,9781111111111,9784444444444]
Fred[9781234664666,9781237878788]
Max[9781234567890]
Sally[9781234567890,9781239977979,9781234545454,978123456455]
Python Dictionary Key,Value pair store

Python code example of a dictionary of lists

To create this in Python code you do the following:

import json

# Create an empty dictionary to hold a dictionary of friends and the books they have read
def addBook(friend,book):

    # If friend isn't in the dictionary add them with an empty list of books
    if friend not in friendLookup:
        friendLookup[friend] = []
    
    # Now add the book to the friends entry in the dictionary
    friendLookup[friend].append(book)

    return

friendLookup = dict()
addBook('Jane','9781234567890')
addBook('Jane','9781111111111')
addBook('Jane','9784444444444')
addBook('Fred','9781234664666')
addBook('Fred','9781237878788')
addBook('Max','9781234567890')
addBook('Sally','9781234567890')
addBook('Sally','9781239977979')
addBook('Sally','9781234545454')
addBook('Sally','978123456455')

print(friendLookup)

with open('friends.json', 'w') as fp:
    json.dump(friendLookup, fp)

Saving a Python Dictionary to Json

As a bonus this code writes out the summary to a json file so that the summary you have created can be used elsewhere without the overhead of rebuilding this summary each time it is needed. This is so easy in Python, just import json, open a file for output and then use the json.dump function.

In my example we have a dictionary of lists by don’t forget the the Python dictionary supports all Python collection objects so you could equally use Sets for example.




You May Also Like…

Find similar blogs in these categories: Python
0 Comments
Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.