How to create a Dictionary in Python
Last Updated :
04 Jul, 2023
Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1)
and have been heavily optimized for memory overhead and lookup speed efficiency.
Create a Dictionary in Python
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by a ‘comma’. Let us see a few examples to see how we can create a dictionary in Python.
Define a Dictionary with Items
In this example, we first declared an empty dictionary D, then added the elements from the Python list L into the dictionary. The first element of each of the sublists is the key and the second element is the value. We will store the key-value pair dynamically.
Python3
D = {}
L = [[ 'a' , 1 ], [ 'b' , 2 ], [ 'a' , 3 ], [ 'c' , 4 ]]
for i in range ( len (L)):
if L[i][ 0 ] in D:
D[L[i][ 0 ]].append(L[i][ 1 ])
else :
D[L[i][ 0 ]] = []
D[L[i][ 0 ]].append(L[i][ 1 ])
print (D)
|
Output:
{'a': [1, 3], 'b': [2], 'c': [4]}
An Overview of Keys and Values
In this example, we will add another element to the existing dictionary in Python. We are provided with the key and value separately and will add this pair to the dictionary my_dict.
Python3
key_ref = 'More Nested Things'
my_dict = {
'Nested Things' : [{ 'name' , 'thing one' }, { 'name' , 'thing two' }]
}
my_list_of_things = [{ 'name' , 'thing three' }, { 'name' , 'thing four' }]
try :
my_dict[key_ref].append(my_list_of_things)
except KeyError:
my_dict = { * * my_dict, * * {key_ref: my_list_of_things}}
print (my_dict)
|
Output:
{
'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}],
'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}]
}
Built-in Dictionary Functions Methods in Python
A dictionary in Python can also be created by the built-in function dict(). In this example, we first created an empty dictionary using curly braces {}. Then we used the dict() method and passed a list to it.
Python3
Dict = {}
my_list = [( 1 , 'Geeks' ), ( 2 , 'For' )]
print (my_list)
print ( "\nDictionary with the use of dict(): " )
Dict = dict (my_list)
print ( Dict )
|
Output:
[(1, 'Geeks'), (2, 'For')]
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For'}
Please Login to comment...