How to create a Python Dictionary of lists?
The dictionaries in Python are highly undervalued. Everybody who is learning python might definitely come across dictionaries as part of the curriculum. But we rarely get a chance to use them or rather we are more accustomed to the arrays, so use more 'Lists'. I was no exception. Lists are still my favorite, but recently I came across a strange situation where I had to have a 'single key, many values' kind of dataset. I will try to give a vague explanation of the problem here.
Given a bag of balls having any number less than 100000, I have to divide the balls into equal sections until I end up with single balls on hand. Adding up the values from the bottom-up (each level is given a weightage), I have to find the maximum sum. At each level, I need to find the maximum value of that particular level and add them up together to find the final value. There may be many ways to achieve this. But the dictionary of lists was an easy one. Ignore this part if it confuses you, I am just including it here to explain the concept of dictionaries. Here is an example with 81 balls in a bag:
What is a Dictionary?
Dictionary is an ordered collection of data values for those who are new to Python, stored like a map of?key: value?pairs. Values in the dictionary can be of any datatype and can also be duplicated. But the keys have to be unique. Refer to the code below to know how to create a dictionary and add a new pair
Output:
Dictionary of lists
To solve the problem explained initially, I wanted to have a data type which accepts multiple values for a single key. I did some google search and stackoverflow came to my rescue again. I found that it is possible to create a dictionary of lists. This is how you do it.
We need to include the Collections module to use this option. This module provides various type of containers like lists, sets, tuples, dictionary, counters and many more.
领英推荐
Output:
Note that there are duplicates in the values but not in the keys.?We have to always 'append' the values instead of directly giving it like this dict2[4] = 'new'
Deletion of dictionary elements
We can either delete a single value of a particular key or an entire key-value pair. We use the normal pop() and remove() methods of lists to remove a single value and 'del' is used to remove the entire pair. See the example below:
Output:
Thus I learned about a useful way to store multivalued key pairs to solve my programming problem. I will write more as I learn along the path. Thanks for reading. Happy if it helped you in some way.
Data Culture Coach focusing on improving data literacy and storytelling skills.
3 年Nice one Kayathri.
DevOps Platform Engineering at UBS
3 年Great article Kayathri ??