A dictionary is an unordered collection of key-value pairs. Keys must be unique and are used to lookup values. Dictionaries are created using curly braces {} and keys are separated from values with colons. Values can be of any data type and keys should be immutable. Items in a dictionary are accessed via keys rather than indices. Dictionaries are mutable, allowing existing items to be modified or new items added. Common operations include membership testing, traversing with for loops, and built-in methods like keys(), values(), items(), get(), update(), pop(), and clear().
A dictionary is an unordered collection of key-value pairs. Keys must be unique and are used to lookup values. Dictionaries are created using curly braces {} and keys are separated from values with colons. Values can be of any data type and keys should be immutable. Items in a dictionary are accessed via keys rather than indices. Dictionaries are mutable, allowing existing items to be modified or new items added. Common operations include membership testing, traversing with for loops, and built-in methods like keys(), values(), items(), get(), update(), pop(), and clear().
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a
huge amount of data. We must know the key to retrieve the value. Creating a Dictionary To create a dictionary, the items entered are separated by commas and enclosed in curly braces. Each item is a key value pair, separated through colon (:). The keys in the dictionary must be unique and should be of any immutable data type, i.e., number, string or tuple. The values can be repeated and can be of any data type. Example: dict1 = {} #curly braces are used for dictionary print(dict1) #dict2 is an empty dictionary created using built-in function dict2 = dict() print(dict2) #dict3 is the dictionary that maps names of the students #to respective marks in percentage dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} print(dict3) Accessing Items in a Dictionary We have already seen that the items of a sequence (string, list and tuple) are accessed using a technique called indexing. The items of a dictionary are accessed via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value. dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} print(dict1['Ram']) Dictionaries are Mutable Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created. Adding a new item We can add a new item to the dictionary as shown in the following example: dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} dict1['Meena'] = 78 print(dict1) Modifying an Existing Item The existing dictionary can be modified by just overwriting the key-value pair dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} dict1['Suhel'] = 78 print(dict1) Dictionary Operations Membership The membership operator in checks if the key is present in the dictionary and returns True, else it returns False. dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} print('Suhel' in dict1) print('Suhel' not in dict1) Traversing a Dictionary We can access each item of the dictionary or traverse a dictionary using for loop. Method 1 dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} for key in dict1: print(key,':',dict1[key]) Method 2 dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} for key,value in dict1.items(): print(key,':',value) Dictionary methods and Built-in functions len() : Returns the length or number of key: value pairs of the dictionary passed as the argument. dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85} print(len(dict1)) dict() : Creates a dictionary from a sequence of key-value pairs. pair1 = [('Mohan',95),('Ram',89),('Suhel',92),('Sangeeta',85)] print(pair1) dict1 = dict(pair1) print(dict1) keys() : Returns a list of keys in the dictionary. dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85} print(dict1.keys()) values() : Returns a list of values in the dictionary . dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85} print(dict1.values()) items() : Returns a list of tuples(key –value) pair. dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85} print(dict1.items()) get() : Returns the value corresponding to the key passed as the argument If the key is not present in the dictionary it will return None. dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85} print(dict1.get('Mohan')) print(dict1.get('Sohan')) update() : appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary. dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85} dict2 = {'Sohan':79,'Geeta':89} dict1.update(dict2) print(dict1) del() : Deletes the item with the given key. dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} del dict1['Ram'] print(dict1) del dict1 ['Mohan'] print(dict1) To delete the dictionary from the memory we write: del Dict_name dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} del dict1 print(dict1) clear() : Deletes or clear all the items of the dictionary. dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} dict1.clear() print(dict1) fromkeys() : The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user. keys = {'a', 'e', 'i', 'o', 'u' } vowels = dict.fromkeys(keys,1) print(vowels) copy() : They copy() method returns a shallow copy of the dictionary. dict1 = {'Name': 'Amit', 'Age': 7}; dict2 = dict1.copy() print ("New Dictionary : %s" %dict2) pop() : pop() method removes and returns an element from a dictionary provided the given key. The pop() method returns: If key is found - removed/popped element from the dictionary If key is not found - value specified as the second argument (default) If key is not found and default argument is not specified - KeyError exception is raised Example 1: sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('apple') print('The popped element is:', element) print('The dictionary is:', sales) Example 2: sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('guava', 'banana') print('The popped element is:', element) print('The dictionary is:', sales) // Here guava is not in the dictionary but banana is the default element. Example 3: sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('guava') print('The popped element is:', element) print('The dictionary is:', sales) // Here guava is not in the dictionary and default element is also not given so it raise error. popitem() : The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary. person = {'name': 'Phill', 'age': 22, 'salary': 3500.0} result = person.popitem() print('Return Value = ',result) print('person = ',person) setdefault() : The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary. person = {'name': 'Phill'} salary = person.setdefault('salary') print('person = ',person) print('salary = ',salary) # key is not in the dictionary # default_value is provided age = person.setdefault('age', 22) print('person = ',person) print('age = ',age) Program : Write a program to enter names of employees and their salaries as input and store them in a dictionary. num = int(input("Enter the number of employees whose data to be stored:")) count = 1 employee = dict() #create an empty dictionary while count <= num: name = input("Enter the name of the Employee: ") salary = int(input("Enter the salary: ")) employee[name] = salary count += 1 print("\n\nEMPLOYEE_NAME\tSALARY") for k in employee: print(k,'\t\t',employee[k]) Program : Write a program to count the number of times a character appears in a given string using dictionary. st = input("Enter a string: ") dic = {} #creates an empty dictionary for ch in st: if ch in dic: #if next character is already in the dictionary dic[ch] = dic[ch] + 1 else: dic[ch] = 1 #if ch appears for the first time for key in dic: print(key,':',dic[key]) Program : Write a function to convert a number entered by the user into its corresponding number in words. For example, if the input is 876 then the output should be ‘Eight Seven Six’. numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\ 5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'} result = '' num = input("Enter any number: ") for ch in num: key = int(ch) #converts character to integer value = numberNames[key] result = result + ' ' + value print("The number is:",num) print("The numberName is:",result)