Python dictionary is an unordered collection of items, which means we can’t index it. In comparison, other compound data types have only value as an element.
A dictionary has a key: value pair, and it can be visualized as a table containing two columns, a key column, and a value column to get the value given the key quickly. However, it isn’t easy to find the exact key given the value.
Python Dictionary is represented using curly brackets {}
Create Dictionary
There are multiple ways to create or instantiate a dictionary object. In this note, we try to explore almost all the methods to create a python dictionary.
Create a dictionary using curly brackets without initialization with elements
Example 1: We have created a dictionary object using curly brackets without data items. Once a dictionary object is instantiated, we add elements in a key, value pair.
dict_obj = {} dict_obj[1] = "One" print(dict_obj) # Output: {1: 'One'} dict_obj[2] = "Two" print(dict_obj) # Output: {1: 'One', 2: 'Two'} dict_obj['three'] = 3 print(dict_obj) # Output: {1: 'One', 2: 'Two', 'three': 3}
In the above example, we have seen that we can use any key and value pair and create a dictionary.
Create a dictionary using curly brackets with elements
Example 2: We are initializing a dictionary object using curly brackets with elements.
dict_obj = {1:"one",2:"two",3:"three"} print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three'} dict_obj[4] = "four" print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
In the above example, we have demonstrated how to initialize a python dictionary object with elements and add new elements to the existing dictionary object.
Create a dictionary using dict function
Example 3: We have used the dict() function to initialize a dictionary object and add its elements.
dict_obj = dict() dict_obj[1] = "One" dict_obj[2] = "Two" dict_obj[3] = "Three" print(dict_obj) # Output: {1: 'One', 2: 'Two', 3: 'Three'}
Create a dictionary using dict function with a list of tuples
Example 4: We have added a list of tuple objects into the dictionary object.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three'}
Create a dictionary using dict function with mixed keys
Example 5: We have added a few elements (key-value pairs) with different types of keys.
dict_obj = dict([(1,"one"),(2,"two"),("address",["CV Raman Nagar","Bangalore","Karnataka"])]) print(dict_obj) # Output: {1: 'one', 2: 'two', 'address': ['Raman Nagar', 'Bangalore', 'Karnataka']}
Access Dictionary
In this section, we will learn how to access elements of a dictionary. Moreover, accessing elements from a dictionary is very easy; it is similar to adding a new element to the dictionary.
Access element with key-id
dict_obj = dict([(1,"one"),(2,"two"),("address",["CV Raman Nagar","Bangalore","Karnataka"])]) print(dict_obj) # Output: {1: 'one', 2: 'two', 'address': ['CV Raman Nagar', 'Bangalore', 'Karnataka']} print(dict_obj['address']) # Output: ['CV Raman Nagar', 'Bangalore', 'Karnataka']
Using the key, we can access the value. In the above example, a key called “address” gets the expected value after supplying the correct key. However, an invalid key returns a key error in the case of an invalid key.
Access element using the get function
There is a function called get, through this function, we can access value.
dict_obj = dict([(1,"one"),(2,"two"),("address",["CV Raman Nagar","Bangalore","Karnataka"])]) print(dict_obj) # Output: {1: 'one', 2: 'two', 'address': ['CV Raman Nagar', 'Bangalore', 'Karnataka']} print(dict_obj.get('address')) # Output: ['CV Raman Nagar', 'Bangalore', 'Karnataka']
The advantage of this function is that even though, the key does not exist, it does not return an error, in spite, it returns none. So it is always good to use the get function.
Add or Edit elements in Dictionary
To add a new element in the dict object, type the key and assign a value.
In the below example, we have added one element which is having key as 3 and a value as “three”.
dict_obj = dict([(1,"one"),(2,"two"),("address",["CV Raman Nagar","Bangalore","Karnataka"])]) print(dict_obj) #Output: {1: 'one', 2: 'two', 'address': ['CV Raman Nagar', 'Bangalore', 'Karnataka']} dict_obj[3] = "Three" print(dict_obj) # Output: {1: 'Two', 2: 'two', 'address': ['CV Raman Nagar', 'Bangalore', 'Karnataka'], 3: 'Three'}
we have added a new key 3 and associated value “three”. If suppose we assign a new value to the same key then it does not give error. Instead, it modifies the value of that particular key in a dictionary. Using the same concept we can either add or modify elements of a dictionary.
Delete or Remove elements from Dictionary
There are many functions to remove elements from the dictionary, such as pop, popitem, del, clear, etc. In the case of the pop function, it removes elements from the dictionary and returns the value of the deleted element, whereas, in the case of popitem, it removes any of the arbitrary keys.
Delete a particular element using the pop function
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} # Remove a particular element val = dict_obj.pop(1) print(dict_obj) # Output: {2: 'two', 3: 'three', 4: 'four'} print(val) # Output: one
Delete arbitrary elements using popitem function
Popitem does not take any key, it arbitrarily removes any element from the dictionary.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} # Remove a particular element val = dict_obj.popitem() print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three'}
Delete a particular element using the del keyword
This is another way to delete an element from the dictionary, it is called del. In the below example, we will understand it. The major problem with this function is that if a key is invalid, it returns an error.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} # Remove a particular element del dict_obj[1] print(dict_obj) # Output: {2: 'two', 3: 'three', 4: 'four'}
Delete all the elements from the dictionary using the clear function
This function clears all the elements from the dictionary which is illustrated in the below example.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} # Remove all the elements dict_obj.clear() print(dict_obj) # Output: {}
Delete dictionary object using the del keyword
del keyword with dictionary object name deletes the dictionary object. If we compare it with the clear function, it simply clears the whole dictionary rather than deleting the dictionary object.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) # Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} # Remove all the elements del dict_obj print(dict_obj) # Output: NameError: name 'dict_obj' is not defined
Inbuilt function for dictionary
Copy entire dictionary elements
Using the copy function we can copy the entire elements from one dictionary object to another dictionary object. It is very similar to the clone function.
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) #Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} dict_obj2 = dict_obj print("dict_obj: ",id(dict_obj), "dict_obj2:",id(dict_obj2)) # Output: dict_obj: 509725888768 dict_obj2: 509725888768 # Using copy function dict_obj2 = dict_obj.copy() print("dict_obj: ",id(dict_obj), "dict_obj2:",id(dict_obj2)) # Output: dict_obj: dict_obj: 509725843200 dict_obj2: 509725841472
In the above example, we have copied dictionary object from dict_obj to dict_obj2.
fromkeys function to create a dictionary from a given list
Using the fromkey function, we can create a dictionary which takes keys from the list and associated values and creates a dictionary.
dict_obj = {}.fromkeys(["one","two","three","four"],1) print(dict_obj) # Output: {'one': 1, 'two': 1, 'three': 1, 'four': 1}
Get dictionary elements into List of tuples using the items function
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) #Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} list_obj = dict_obj.items() print(list_obj) # Output: dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
Get dictionary keys in a list using the keys function
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) #Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} list_obj = dict_obj.keys() print(list_obj) #Output: dict_keys([1, 2, 3, 4])
Get dictionary values in a list using the values function
dict_obj = dict([(1,"one"),(2,"two"),(3,"three"),(4,"four")]) print(dict_obj) #Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'} list_obj = dict_obj.values() print(list_obj) # Output: dict_values(['one', 'two', 'three', 'four'])
To get all the functions available with the dictionary data type
d = {} print(dir(d)) # Output: ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Dictionary comprehension
Iterate whole dictionary
dict_obj = {'one':1,'two':2,'three':3,'four':4,'five':5} for tuples_obj in dict_obj.items(): print(tuples_obj) # Output: #('one', 1) #('two', 2) #('three', 3) #('four', 4) #('five', 5)
Conditional selection of items
dict_obj = {'one':1,'two':2,'three':3,'four':4,'five':5} cond_sel_dict_obj = {k:v for k,v in dict_obj.items() if v > 1} print(cond_sel_dict_obj) #Output: {'two': 2, 'three': 3, 'four': 4, 'five': 5}
In the above example, we have selected all the key and value pairs whose value is greater than 1
dict_obj = {'one':1,'two':2,'three':3,'four':4,'five':5} cond_sel_dict_obj = {k+'_new':v+1 for k,v in dict_obj.items() if v > 1} print(cond_sel_dict_obj) # Output: {'two_new': 3, 'three_new': 4, 'four_new': 5, 'five_new': 6}
12,220 total views, 2 views today