AppDividend
Latest Code Tutorials

Python Dictionary of Lists

0

You can say that Python dictionaries are associative arrays. You can define a dictionary by surrounding a comma-separated list of key-value pairs in curly braces ({ }). The colon(:) separates each key from its associated value. Let’s see how to create a dictionary of lists.

Python Dictionary of Lists

Python dictionary of lists is a dictionary whose values are lists. For example, {“x”: [11, 21], “y”: [19, 46]}  is a dictionary of lists. Python dictionary is an unordered, changeable, and indexed collection.

To create a dictionary, you need to add key-value pairs inside the curly braces. To access the elements of a dictionary, use the key name inside square brackets.

Create a dictionary of lists

To initialize a dictionary of lists, assign each key to a list of items to create a dictionary of lists.

# app.py

dictOfList = {"x": [11, 21], "y": [19, 46]}
print(dictOfList)

Output

{'x': [11, 21], 'y': [19, 46]}

In this example, x and y are dict keys, and lists are values.

Using the list as keys in the dictionary

The restriction with keys is that only immutable data types can be used as keys in the Python dictionary, which means we cannot use a dictionary of the list as a key.

# app.py

dictOfListKeys = {[1, 2]: 'AppDividend'}
print(dictOfListKeys)

Output

TypeError: unhashable type: 'list'

You can see that we got a TypeError: unhashable type: ‘list’.

But the same can be done very wisely with values in the dictionary.

Use subscript to create a dictionary of lists.

You can add a list as a value in the dictionary.

# app.py

myDict = {}

# Adding list as value
myDict["key1"] = [11, 21]
myDict["key2"] = ["MBB", "KL"]

print(myDict)

Output

{'key1': [11, 21], 'key2': ['MBB', 'KL']}

Using defaultdict

Defaultdict in Python is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns the dictionary-like object.

Syntax

defaultdict(default_factory)

Parameters

default_factory: It is a function returning the default value for the dictionary defined. If the default_factory argument is absent, then the dictionary raises a KeyError.

Example

# Importing defaultdict from the collections module
from collections import defaultdict

mList = [('Millie', 1), ('Bobby', 2), ('Brown', 3)]
deDict = defaultdict(list)

# iterating over list of tuples
for key, val in mList:
    deDict[key].append(val)

print(deDict)

Output

defaultdict(<class 'list'>, {'Millie': [1], 'Bobby': [2], 'Brown': [3]})

In this example, we are creating a dictionary of lists using defaultdict(). Here, the keys in the dictionary are different, but if the keys are the same, then it will combine the values in one list and return the dictionary.

# Importing defaultdict from the collections module
from collections import defaultdict

mList = [('Va', 1), ('Tech', 2), ('Va', 3)]
deDict = defaultdict(list)

# iterating over list of tuples
for key, val in mList:
    deDict[key].append(val)

print(deDict)

Output

defaultdict(<class 'list'>, {'Va': [1, 3], 'Tech': [2]})

That is it for a dictionary of lists in Python.

See also

Python list to dictionary

Python Dictionary to DataFrame

Python Dict to JSON

Leave A Reply

Your email address will not be published.

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