Python - Ways to create a dictionary of Lists

PythonServer Side ProgrammingProgramming

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. You can access the items of a dictionary by referring to its key name, inside square brackets.

Example

 Live Demo

# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
myDict["key2"] = ["Vishesh", "For", "Python"]
print(myDict)
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
# creating a list
lst = ['vishesh', 'For', 'python']  
# Adding this list as sublist in myDict
myDict["key1"].append(lst)  
print(myDict)
# 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)
# 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

{'key2': ['Vishesh', 'For', 'Python'], 'key1': [1, 2]}
{'key1': [1, 2, ['vishesh', 'For', 'python']]}
{1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}
{'1': [1, 2], '3': [3, 4], '2': [2, 3]}
raja
Published on 06-Aug-2020 17:20:32
Advertisements