Add list to dictionary Python | Example code

One way is Add list to dictionary doing by Adding nested list as value using append() method in Python. Create a new list and we can simply append that list to the value.

Example Add list to dictionary Python

Simple example code. The restriction with keys in the python dictionary is only immutable data types can be used as a key. So, we cannot use a dictionary of the list as a key. If we try to do this we will get a “TypeEerror”.

myDict = {"A": 0}

# Adding list as value
myDict["key1"] = [1, 2]

# A list
lst = ['X', 'Y']

# Adding this list as sublist in myDict 
myDict["key1"].append(lst)

print(myDict)
print(type(myDict))

Output:

Add list to dictionary Python

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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