90 likes | 108 Views
A dictionary is a collection which is unordered, changeable and does not allow duplicates. In this tutorial we have discussed in detail the ways to create dictionary, perform different operations using methods along with their examples.<br>
E N D
Dictionary Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is unordered, changeable and does not allow duplicates. Dictionary is mutable. Dictionaries are written with curly brackets, and have keys and values. Key should be unique and immutable datatype. If we try to assign a new value to same key prior value will be deleted and the new one will be stored.
Values in the dictionary can be duplicated but key cannot be duplicated. Key can be any immutable object like integer, float, character, complex,tuple. Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Creating a dictionary: d={1:100, ’c’:20, (10,20,30):[100,200,300],4:30} print(d) O/P: {1:100, ’c’:20, (10,20,30):[100,200,300],4:30} Values in the dictionary can be accessed using keys. Eg:(d[‘c’]) O/P:20 In Python Dictionary, deletion of keys can be done by using the del keyword. Using del keyword, specific values from a dictionary as well as whole dictionary can be deleted. Eg: del d[1] print(d) O/P:{’c’:20, (10,20,30):[100,200,300],4:30}
Dictionary Methods clear():Removes all the elements from the dictionary copy():Returns a copy of the dictionary fromkeys():Returns a dictionary with the specified keys and value get():Returns the value of the specified key items():Returns a list containing a tuple for each key value pair keys():Returns a list containing the dictionary's keys
pop():Removes the element with the specified key popitem():Removes the last inserted key-value pair setdefault():Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update():Updates the dictionary with the specified key-value pairs values():Returns a list of all the values in the dictionary
Examples d = {1:100, 2.3:200, 10+20j:300, 'a': 'Python', (10,20,30):[100,200,3 00]} print(d.get('a')) O/P: Python print(d.setdefault('b')) O/P: None d1 = d.copy() # shallow copy of dictionary print(d1 is d) O/P:False d={1:100,2.3:200,10+20j:300,'a':'Python',(10,20,30):[100,200,300]} d.pop(1) print(d) O/P:{2.3: 200, (10+20j): 300, 'a': 'Python', (10, 20, 30): [100, 200, 300]}
d={1:100,2.3:200,10+20j:300,'a':'Python',(10,20,30):[100,200,300]} d.popitem() print(d) O/P: {1: 100, 2.3: 200, (10+20j): 300, 'a': 'Python'}
Thanks for Watching!!! For more follow us on our social media platforms: Instagram : learnbay_datascience Facebook : learnbay LinkedIn : Learnbay Twitter : Learnbay1