How to add a list to a Python dictionary
Now, let’s see different ways of creating a dictionary of list.
Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key.
# Creating a dictionary
myDict = {[1, 2]: 'Geeks'}
print(myDict)
Output:
- TypeError: unhashable type: 'list'
But the same can be done very wisely with values in dictionary. Let’s see all the different ways we can create a dictionary of Lists.
Method #1: Using subscript
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
myDict["key2"] = ["Geeks", "For", "Geeks"]
print(myDict)
Output:
- {'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]}
Method #2: Adding nested list as value using append() method.
Create a new list and we can simply append that list to the value.
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
# creating a list
lst = ['Geeks', 'For', 'Geeks']
# Adding this list as sublist in myDict
myDict["key1"].append(lst)
print(myDict)
Output:
- {'key1': [1, 2, ['Geeks', 'For', 'Geeks']]}
Method #3: Using setdefault()method
Iterate the list and keep appending the elements till given range using setdefault() method.
# Creating an empty dict
myDict = dict()
# Creating a list
valList = ['1', '2', '3']
# Iterating the elements in list
for val in valList:
for ele in range(int(val), int(val) + 2):
myDict.setdefault(ele, []).append(val)
print(myDict)
Output:
- {1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}
Method #4: Using list comprehension
# Creating a dictionary of lists
# using list comprehension
d = dict((val, range(int(val), int(val) + 2))
for val in ['1', '2', '3'])
print(d)
Output:
- {'1': [1, 2], '3': [3, 4], '2': [2, 3]}
- Thanks ?.
Articoli simili
- Cosa determina se una celebrità è nella A-List, B-List, C-List o D-List?
- How to fix “KeyError: 0” Python with a dictionary
- How to find prime numbers in a list in Python
- È consigliabile imparare Tkinter in Python per avanzare la propria carriera o per ottenere una migliore offerta di lavoro come sviluppatore Python?