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:
Person | Value1 | Value2 | Value3 | Valuen |
Jane | 9781234567890 | 9781111111111 | 9784444444444 | |
Fred | 9781234664666 | 9781237878788 | ||
Max | 9781234567890 | |||
Sally | 9781234567890 | 9781239977979 | 9781234545454 | 978123456455 |
What does a multi-dimensional dictionary look like in Python?
In Python this is easily implemented as a Python Dictionary which looks like this:
Key | Value |
Jane | [9781234567890,9781111111111,9784444444444] |
Fred | [9781234664666,9781237878788] |
Max | [9781234567890] |
Sally | [9781234567890,9781239977979,9781234545454,978123456455] |
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.
Frequently asked questions about Python Dictionaries containing multiple values per key.
Yes, you can have multiple values. Please see the above article, but in summary the value you store against the key doesn’t have to be the value(s) itself but could be another object, for example a list, which itself then contains however many values you want.
0 Comments