Python | Ways to create a dictionary of Lists - GeeksforGeeks

11 Mar, 2019
Till now, we have seen the ways to creating dictionary in multiple ways and different operations on the key and values in 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 dictionarymyDict = {[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 dictionarymyDict = {}  # Adding list as valuemyDict["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 dictionarymyDict = {}  # Adding list as valuemyDict["key1"] = [1, 2]  # creating a listlst = ['Geeks', 'For', 'Geeks']  # Adding this list as sublist in myDictmyDict["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 dictmyDict = dict()  # Creating a listvalList = ['1', '2', '3']  # Iterating the elements in listfor 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 comprehensiond = 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]}
 Method #5: Using defaultdict
Note that the same thing can also be done with simple dictionary but using defaultdict is more efficient for such cases.
# Importing defaultdictfrom collections import defaultdict  lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]orDict = defaultdict(list)  # iterating over list of tuplesfor key, val in lst:    orDict[key].append(val)  print(orDict)
Output:
defaultdict(, {'For': [2], 'Geeks': [1, 3]})
Note that there are only two key:value pairs in output dictionary but the input list contains three tuples. The first element(i.e. key) is same for first and third tuple and two keys can never be same. Method #6: Using Json
#importing jsonimport json  #Initialisation of listlst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]  #Initialisation of dictionarydict = {}  #using json.dump()hash = json.dumps(lst)  #creating a hashdict[hash] = "converted"  #Printing dictionaryprint(dict)  #Added by Paras Jain(everythingispossible)
Output:
{'[["Geeks", 1], ["For", 2], ["Geeks", 3]]': 'converted'}
 
everythingispossible
Python dictionary-programs
Python list-programs
python-dict
python-list
Python
python-dict
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python