Dictionary Data Structure ========================= When we want to create the data structures with key-value pairs, we can use "dictionaries". Syntax: dictionary-name = {key1 : val1, key2 : val2, ......} Ex: Web application registration form user-name : xxxxxx mobile: xxxxxx age : xxx -> Dictionary is also a pre-defined data structure because it has pre-defined class "dict". How to access dictionary elements: ---------------------------------- -> no index is possible to access the dictionary. -> to access the dictionary elements, we can use "keys". Syntax: dictionary-name[key] d = {'user':'ravi','age':31,'weight':65.6} print(type(d)) # print(d[0]) print(d['user']) print(d['age']) print(d['weight']) Is dictionary ordered? ---------------------- Yes Is dictionary mutable or immutable? ------------------------------------ mutable d = {'user':'ravi','age':31,'weight':65.6} print(d) print(id(d)) d['user'] = 'Karthik' print(d) print(id(d)) Dictionary functions: --------------------- 1) len(): -------- -> to get the length of the dictionary, we can use "len()" Syntax: len(dictionary-name) 2) get(): --------- i) when we want to access any value of the dictionary with respect to the key, we can use "get()". Syntax: dictionary-name.get(key) ii) When we want to set new default value for any existing key of the dictionary, we can use get(). But if the specified key is already existed with some value, then we can get with existed value. Otherwise we can get the specified key with default value. Syntax: dictionary-name.get(key, default-value) 3) keys() ---------- Syntax: dictionary-name.keys() 4) values() ----------- Syntax: dictinary-name.values() d = {'apple' : 121,'banana':222,'cherry':212,'grape':300,'apple':321} print(d.keys()) print(d.values()) Note: ----- In dictionary: keys ==> unique values ==> unique or duplicate items(): -------- Syntax: dictionary-name.items() d = {'apple' : 121,'banana':222,'cherry':212,'grape':300,'apple':321} print(d.items()) popitem(): ---------- Syntax: d.popitem() d = {'apple' : 121,'banana':222,'cherry':212,'grape':300,'apple':321} print(d) d.popitem() print(d) d['kiwi'] = 121 print(d)