Dictionary: Dictionaries are used to store multiple items in key : value form separated by a , (keys and values may be of same type elements ie homogeneous data types or different types elements ie heterogeneous data types) in a single variable. It is a comma separated list of key:value pairs enclosed in braces { } . Example:
dict1={“garg”:1, “academy”:2}
#dictionary of homogeneous elements
dict2={“garg”:1, 2:”academy”}
#dictionary of heterogeneous elements
dict3={}
#empty dictionary
Creating Dictionaries: We can create both empty dictionaries as well as non empty dictionaries by
1) directly assigning the literals/values and
2) by using the built in method dict() of python.
Creating Empty Dictionaries by directly assigning: We can create empty dictionaries by assigning as:
>>> dict1={} >>> dict1 {}
Creating Empty Dictionaries in Python using dict(): We can create empty dictionaries using dict() in various ways as
>>> dict2=dict() >>> dict2 {} >>> dict3=dict([]) >>> dict3 {} >>> dict4=dict(()) >>> dict4 {} >>> dict5=dict({}) >>> dict5 {}
Creating Non Empty dictionaries in Python by assigning: We can create non empty dictionaries in various ways as
>>>#Creating homogeneous dictionaries >>> dict1={"garg":1,"academy":2} >>> dict1 {'garg': 1, 'academy': 2} >>>#Creating heterogeneous dictionaries >>> dict2={"garg":1,2:"academy"} >>> dict2 {'garg': 1, 2: 'academy'}
Creating Non Empty dictionaries in Python using dict(): We can create non empty dictionaries in various ways as
>>>#creating homogeneous dictionary using dictionary >>> dict1=dict({"gargs":1,"academy":2}) >>> dict1 {'gargs': 1, 'academy': 2} >>>#creating heterogeneous dictionary using dictionary >>> dict2=dict({"gargs":1,2:"academy"}) >>> dict2 {'gargs': 1, 2: 'academy'}
We cant create a non empty dictionary using lists, tuples, sets or strings because we are having only values, but not the keys in lists, tuples, sets and strings. So python will error as:
>>>#creating dictionary using list >>> dict1=dict([2,3,4]) Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> dict1=dict([2,3,4]) TypeError: cannot convert dictionary update sequence element #0 to a sequence >>>#creating dictionary using tuple >>> dict1=dict((2,3,4)) Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> dict1=dict((2,3,4)) TypeError: cannot convert dictionary update sequence element #0 to a sequence >>>#creating dictionary using string >>> dict1=dict("gargs") Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> dict1=dict("gargs") ValueError: dictionary update sequence element #0 has length 1; 2 is required >>>#creating dictionary using set >>> dict1=dict({2,3,4}) Traceback (most recent call last): File "<pyshell#49>", line 1, in <module> dict1=dict({2,3,4}) TypeError: cannot convert dictionary update sequence element #0 to a sequence
Mutable: Dictionaries are mutable objects ie. once created, we can change, increase/decrease the elements of the dictionary, without changing its base address.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> id(dict1) 1343175979328 >>>#updating an already existing value in dictionary >>> dict1[5]="math and computer academy" >>> dict1 {1: 'garg', 5: 'math and computer academy'} >>> id(dict1) 1343175979328 >>>#adding a new key:value pair in dictionary >>> dict1[7]=9467863365 >>> dict1 {1: 'garg', 5: 'math and computer academy', 7: 9467863365} >>> id(dict1) 1343175979328 >>>#removing from dictionary >>> del dict1[1] >>> dict1 {5: 'math and computer academy', 7: 9467863365} >>> id(dict1) 1343175979328
Accessing Elements of Python Dictionary: We can access any element using its index as:
dictioanryname[valid_index]
>>> dict1={1:"garg",5:"academy"} >>> dict1[1] 'garg' >>> dict1[5] 'academy'
If the index does not exist, then an error message is shown as:
>>> dict1={1:"garg",5:"academy"} >>> dict1[4] Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> dict1[4] KeyError: 4 #Notice garg is a value, not the index in the given dictionary >>> dict1["garg"] Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> dict1["garg"] KeyError: 'garg'
Dictionary Operations: There are 3 types of operations possible on dictionaries.
1. Membership
2. Traversal
3. Manipulation
Membership on Dictionaries: In Python, there are two membership operators. (in, not in), which are used to test whether or not the given key is present in the dictioanry.
1) key in dictionayname
2) key not in dictionaryname
>>> dict1={1:"garg",5:"academy"} >>> 1 in dict1 True >>> 1 not in dict1 False
in operator returns True only if the element is present as a key in the dictionary
>>> dict1={1:"garg",5:"academy"} >>> "garg" in dict1 False >>> "garg" not in dict1 True
Traversing a dictionary using loops: We can traverse (ie. access or print or perform any other operation on each individual value of the dictionary exactly once) using loops as:
>>> dict1={1:"garg",5:"academy"} >>> for key in dict1.keys(): print(dict1[key]) garg academy
Manipulating Dictionaries: We can change the elements of the dictionary as:
dictionaryname[validindex]=newvalue
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1[5]="math and computer academy" >>> dict1 {1: 'garg', 5: 'math and computer academy'}
If the index is not valid, python will add the new key:value pair as an element in the dictionary.
dictionaryname[invalidindex]=newvalue
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1[7]=9467863365 >>> dict1 {1: 'garg', 5: 'math and computer academy', 7: 9467863365}
del : It is used to delete an element with given valid index position from a dictionary or delete the dictionary entirely.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del dict1[1] >>> dict1 {5: 'academy'}
If the index does not exist, python will give error as:
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del dict1[2] Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> del dict1[2] KeyError: 2
Del is also used to delete the dictionary entirely. After deleting the entire dictionary, we will no longer be able to use the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del dict1 >>> dict1 Traceback (most recent call last): File "<pyshell#45>", line 1, in <module> dict1 NameError: name 'dict1' is not defined
Applying built in functions on Dictionaries in Python: Built in functions are predefined functions in python that are available for use without the need for importing any module. We can apply various built in functions on dictionaries such as len(), dict(), sum(), min(), max(), type(), id(), sorted(), del() etc.
len() is used to find the number of elements of the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> len(dict1) 2 >>> dict2={} >>> dict2 {} >>> len(dict2) 0
dict() : It is used to create dictionaries.
>>> dict2=dict() >>> dict2 {} >>> dict3=dict([]) >>> dict3 {} >>> dict4=dict(()) >>> dict4 {} >>> dict5=dict({}) >>> dict5 {} >>>#creating homogeneous dictionary using dictionary >>> dict6=dict({"gargs":1,"academy":2}) >>> dict6 {'gargs': 1, 'academy': 2} >>>#creating heterogeneous dictionary using dictionary >>> dict7=dict({"gargs":1,2:"academy"}) >>> dict7 {'gargs': 1, 2: 'academy'}
sum() is used to find the sum of keys of the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> sum(dict1) 6
If the keys are incompatible for addition, then an error message is shown as:
>>> dict1={1:"garg","academy":5} >>> dict1 {1: 'garg', 'academy': 5} >>> sum(dict1) Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> sum(dict1) TypeError: unsupported operand type(s) for +: 'int' and 'str'
min() is used to find the minimum from the keys of the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> min(dict1) 1
If the keys are incompatible for finding minimum, then an error message is shown as:
>>> dict1={1:"garg","academy":5} >>> dict1 {1: 'garg', 'academy': 5} >>> min(dict1) Traceback (most recent call last): File "<pyshell#64>", line 1, in <module> min(dict1) TypeError: '<' not supported between instances of 'str' and 'int'
max() is used to find the maximum from the keys of the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> max(dict1) 5
If the keys are incompatible for finding maximum, then an error message is shown as:
>>> dict1={1:"garg","academy":5} >>> dict1 {1: 'garg', 'academy': 5} >>> max(dict1) Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> max(dict1) TypeError: '>' not supported between instances of 'str' and 'int'
type() is used to find the data type of the object passed as an argument.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> type(dict1) <class 'dict'> >>> dict2={} >>> dict2 {} >>> type(dict2) <class 'dict'>
id() is used to find the address or location where the first element of the list is stored in memory.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> id(dict1) 1343175979328
sorted(): It is used to create a list from the keys of a given dictionary in sorted order.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> sorted(dict1) [1, 5]
We can also store the result in a list variable as:
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> list1=sorted(dict1) >>> list1 [1, 5]
But the original dictionary remains unchanged.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> list1=sorted(dict1) >>> list1 [1, 5] >>> dict1 {1: 'garg', 5: 'academy'}
del() : It is used to delete an element with given valid index position from a dictionary or delete the dictionary entirely.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del (dict1[1]) >>> dict1 {5: 'academy'}
If the index does not exist, python will give error as:
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del (dict1[2]) Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> del (dict1[2]) KeyError: 2
Del is also used to delete the dictionary entirely. After deleting the entire dictionary, we will no longer be able to use the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> del (dict1) >>> dict1 Traceback (most recent call last): File "<pyshell#45>", line 1, in <module> dict1 NameError: name 'dict1' is not defined
Dictionary Functions in Python: We can apply various functions on dictionaries such as:
- keys()
- values()
- items()
- get()
- update()
- clear()
- fromkeys()
- copy()
- pop()
- popitem()
- setdefault()
To see a list of all functions of a Dictionary:
>>> dir(dict) ['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
To see a description of all the functions of the dictionary:
>>> help(dict) Help on class dict in module builtins: class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) -> new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) | | Methods defined here: | | __contains__(self, key, /) | True if the dictionary has the specified key, else False. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __ior__(self, value, /) | Return self|=value. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __or__(self, value, /) | Return self|value. | | __repr__(self, /) | Return repr(self). | | __reversed__(self, /) | Return a reverse iterator over the dict keys. | | __ror__(self, value, /) | Return value|self. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes | | clear(...) | D.clear() -> None. Remove all items from D. | | copy(...) | D.copy() -> a shallow copy of D | | get(self, key, default=None, /) | Return the value for key if key is in the dictionary, else default. | | items(...) | D.items() -> a set-like object providing a view on D's items | | keys(...) | D.keys() -> a set-like object providing a view on D's keys | | pop(...) | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. | | If key is not found, default is returned if given, otherwise KeyError is raised | | popitem(self, /) | Remove and return a (key, value) pair as a 2-tuple. | | Pairs are returned in LIFO (last-in, first-out) order. | Raises KeyError if the dict is empty. | | setdefault(self, key, default=None, /) | Insert key with a value of default if key is not in the dictionary. | | Return the value for key if key is in the dictionary, else default. | | update(...) | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v | In either case, this is followed by: for k in F: D[k] = F[k] | | values(...) | D.values() -> an object providing a view on D's values | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) from builtins.type | See PEP 585 | | fromkeys(iterable, value=None, /) from builtins.type | Create a new dictionary with keys from iterable and values set to value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
keys(): It is used to return a list containing the keys of a dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.keys() dict_keys([1, 5])
It returns empty list, if the dictionary is empty.
>>> dict2={} >>> dict2 {} >>> dict2.keys() dict_keys([])
values(): It is used to return a list containing the values of a dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.values() dict_values(['garg', 'academy'])
It returns empty list, if the dictionary is empty.
>>> dict2={} >>> dict2 {} >>> dict2.values() dict_values([])
items(): It is used to return a list containing the items of a dictionary. An item of a dictionary is a tuple having its key and value
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.items() dict_items([(1, 'garg'), (5, 'academy')])
It returns empty list, if the dictionary is empty.
>>> dict2={} >>> dict2 {} >>> dict2.items() dict_items([])
get(): It is used to return the value of a specified key from a dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.get(1) 'garg'
It will not return anything, if the key does not exist in the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.get("garg")
It will give error, if you will not specify the key.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.get() Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> dict1.get() TypeError: get expected at least 1 argument, got 0
update(): It is used to add the given items in the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.update({2:"math",3:"computer"}) >>> dict1 {1: 'garg', 5: 'academy', 2: 'math', 3: 'computer'}
It will update the value if specified key already exists in the dictionary.
>>> dict1 {1: 'garg', 5: 'academy', 2: 'math', 3: 'computer'} >>> dict1.update({3:9467863365}) >>> dict1 {1: 'garg', 5: 'academy', 2: 'math', 3: 9467863365}
It will not do anything if the specified dictionary is empty
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.update({}) >>> dict1 {1: 'garg', 5: 'academy'}
clear(): It is used to remove all the items from the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.clear() >>> dict1 {}
fromkeys(): It creates a new dictionary with keys from iterable and values set to value..
fromkeys(iterable, value=None)
>>> dict1=dict.fromkeys([1,2,3,4],10) >>> dict1 {1: 10, 2: 10, 3: 10, 4: 10} >>> dict2=dict.fromkeys([1,2,3,4],[10,20,30,40]) >>> dict2 {1: [10, 20, 30, 40], 2: [10, 20, 30, 40], 3: [10, 20, 30, 40], 4: [10, 20, 30, 40]}
If we dont specify any value, then None will be set as value for all the keys.
>>> dict1=dict.fromkeys([1,2,3,4]) >>> dict1 {1: None, 2: None, 3: None, 4: None}
If we will not specify the keys, then python will error as
>>> dict1=dict.fromkeys() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> dict1=dict.fromkeys() TypeError: fromkeys expected at least 1 argument, got 0
copy(): It is used to create a copy of a dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict2=dict1.copy() >>> dict2 {1: 'garg', 5: 'academy'}
pop(): It is used to remove/pop the item with given key from the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1.pop(1) 'garg' >>> dict1 {5: 'academy'}
If we don’t specify any index position, then python will give error as:
>>> dict1={1:"garg",5:"academy"} >>> dict1.pop(30) Traceback (most recent call last): File "<pyshell#65>", line 1, in <module> dict1.pop(30) KeyError: 30
popitem(): It is used to remove/pop the last item from the dictionary.
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.popitem() (5, 'academy') >>> dict1 {1: 'garg'}
If the dictionary is empty, then python will give error as:
>>> dict2={} >>> dict2.popitem() Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> dict2.popitem() KeyError: 'popitem(): dictionary is empty'
setdefault(): It is used to return the value of the specified key from a dictionary, if the key exists. Otherwise, add the key in the dictionary
>>> dict1={1:"garg",5:"academy"} >>> dict1 {1: 'garg', 5: 'academy'} >>> dict1.setdefault(1) 'garg' >>> dict1 {1: 'garg', 5: 'academy'} >>>#specified key 10 does not exist in the dictionary. >>>#So python will add the new key in the dictionary >>>#Default value of new key is None >>> dict1.setdefault(10) >>> dict1 {1: 'garg', 5: 'academy', 10: None} >>>#We can also specify a value for the specified key as >>> dict1.setdefault(20,"math") 'math' >>> dict1 {1: 'garg', 5: 'academy', 10: None, 20: 'math'}
How to get key of a given value from a dictionary: We will
1) create two lists listname1 and listname2 from the keys and values of a dictionary
2) using index() method of lists, we will find the index of given value in listname2.
3) find the key by accessing the element of returned index position ( in step 2) from the listname1
Write the statements as
listname1=list(dictionaryname.keys())
listname2=list(dictionaryname.values())
indexpos=listname2.index(value)
listname1[indexpos]
Example:
>>> dict1={1:2,3:4} >>> list1=list(dict1.keys()) >>> list2=list(dict1.values()) >>>indexpos=list2.index(4) >>> list1[indexpos] 3
Single line code to get key of a given value from a dictionary:
list(dictionaryname.keys())[list(dictionaryname.values()).index(value)]
>>> dict1={1:2,3:4} >>> list(dict1.keys())[list(dict1.values()).index(4)] 3
Suggested programs: Program 1: Create a dictionary of names and salaries of employees and access it.
dict1={} n=int(input("enter number of employees")) for i in range(n): name=input("enter name of employee") salary=float(input("enter salary of the employee")) dict1[name]=salary for key in dict1: print(key," has salary = ",dict1[key]," Rs.")
Output:
enter number of employees3 enter name of employeeSheetal enter salary of the employee200000 enter name of employeeAmit enter salary of the employee150000 enter name of employeeNidhi enter salary of the employee100000 Sheetal has salary = 200000.0 Rs. Amit has salary = 150000.0 Rs. Nidhi has salary = 100000.0 Rs.
Suggested programs: Program 2: Find the number of occurrences of all the characters in a string using a dictionary
string1 = input("enter a string ") dict1={} for ch in string1: if ch not in dict1: dict1[ch] = string1.count(ch) for key in dict1: print(key, " appears in the ", string1, " " ,dict1[key], " times")
Output:
enter a string gargs academy g appears in the gargs academy 2 times a appears in the gargs academy 3 times r appears in the gargs academy 1 times s appears in the gargs academy 1 times appears in the gargs academy 1 times c appears in the gargs academy 1 times d appears in the gargs academy 1 times e appears in the gargs academy 1 times m appears in the gargs academy 1 times y appears in the gargs academy 1 times