Dictionary in Pyhton

Dictionary in Pyhton


In python, a dictionary is a mixed collection of elements. Unlike other collection data types such as a list or tuple, the dictionary type stores a key along with its element. The keys in a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the elements. The key value pairs are enclosed with curly braces { }.

Syntax of defining a dictionary:

Dictionary_Name = { Key_1: Value_1,
Key_2:Value_2,
……..
Key_n:Value_n
}

Key in the dictionary must be unique case sensitive and can be of any valid Python type.

Creating a Dictionary

# Empty dictionary
Dict1 = { }
# Dictionary with Key
Dict_Stud = { RollNo: 1234, Name:Murali, Class:XII, Marks:451}

Dictionary Comprehensions

In Python, comprehension is another way of creating dictionary. The following is the syntax of creating such dictionary.

Syntax

Dict = { expression for variable in sequence [if condition] }

The if condition is optional and if specified, only those values in the sequence are evaluated using the expression which satisfy the condition.

Example

Dict = { x : 2 * x for x in range(1,10)}
Output of the above code is
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

Accessing, Adding, Modifying and Deleting elements from a Dictionary

Accessing all elements from a dictionary is very similar as Lists and Tuples. Simple print function is used to access all the elements. If you want to access a particular element, square brackets can be used along with key.

Example : Program to access all the values stored in a dictionary

MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

Output:

{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
School: CGHSS
Address: Rotler St., Chennai 112

Note that, the first print statement prints all the values of the dictionary. Other statements are printing only the specified values which is given within square brackets.

In an existing dictionary, you can add more values by simply assigning the value along with key. The following syntax is used to understand adding more elements in a dictionary.

dictionary_name [key] = value/element

Example : Program to add a new value in the dictionary

MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS', 'Address' : '
Rotler St., Chennai 112'}
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly added value
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

Modification of a value in dictionary is very similar as adding elements. When you assign a value to a key, it will simply overwrite the old value.

In Python dictionary, del keyword is used to delete a particular element. The clear( ) function is used to delete all the elements in a dictionary. To remove the dictionary, you can use del keyword with dictionary name.

Syntax:

# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name

Example : Program to delete elements from a dictionary and finally deletes the dictionary.

Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary

Output:

Dictionary elements before deletion:

{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}

Dictionary elements after deletion of a element:

{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}

Dictionary after deletion of all elements:

{ }

Traceback (most recent call last):

File "E:/Python/Dict_Test_02.py", line 8, in <module>

print(Dict)

NameError: name 'Dict' is not defined

Difference between List and Dictionary

(1) List is an ordered set of elements. But, a dictionary is a data structure that is used for matching one element (Key) with another (Value).

(2) The index values can be used to access a particular element. But, in dictionary key represents index. Remember that, key may be a number of a string.

(3) Lists are used to look up a value whereas a dictionary is used to take one value and look up another value.

Python : Dictionary in Pyhton Program List




Program [1]

WAP that repeatedly asks the user to enter product names and prices. Store all of them in a dictionary whose keys are product names and values are prices. And also write a code to search an item from the dictionary.


View Solution


Program [2]

WAP to create a dictionary named year whose keys are month names and values are their corresponding number of days.


View Solution


Program [3]

Write a Python program to enter names of employees and their salaries as input and store them in a dictionary


View Solution


Program [4]

Write a program to count the number of times a character appears in a given string


View Solution


Program [5]

Write a program 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'.


View Solution


Program [6]

Repeatedly ask the user to enter a team name and how many games the team has won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are a list of the form [wins, losses ].


(i) using the dictionary created above, allow the user to enter a team name and print out the team’s winning percentage.

(ii) using dictionary create a list whose entries are the number of wins for each team.

(iii) using the dictionary, create a list of all those teams that have winning records.


View Solution


Program [7]

Write a program that repeatedly asks the user to enter product names and prices. Store all of these  in a dictionary whose keys are the product names and whose values are the price .

When the user is done entering products and price, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in dictionary.


View Solution


Program [8]

Create a dictionary whose keys are month name and whose values are number of days in the corresponding month:

(a) ask the user to enter the month name and use the dictionary to tell how many days are in month .

(b) print out all of the keys in alphabetical order  .

(c) print out all of the month with 31 days.

(d) print out the (key - value) pair sorted  by the number of the days in each month .


View Solution


Program [9]

Can you store the detail of 10 students in a dictionary at the same time? details include – rollno, name ,marks ,grade etc. Give example to support your answer.


View Solution


Program [10]

Given the dictionary x = {‘k1’: ‘v1’, ‘k2’ : ‘v2’, ‘k3’ : ‘v3’} ,create a dictionary with the opposite mapping.

Write a program to create the dictionary .


View Solution


Program [11]

Given two dictionaries say d1 and d2

Write a program that lists the over lapping keys of the two dictionaries if a key of d1 is also a key of d2 , the list it .


View Solution


Program [12]

Write a program that checks if two same values in a dictionary have different keys. 


View Solution


Program [13]

Write a program to check if a dictionary is contained in another dictionary.

 

e.g., if

 

d1 = {1:11, 2:12}

d2 = {1:11, 2:12, 3:13, 4:15}

 

Then d1 is contained in d2.


View Solution


Program [14]

A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements.

 

e.g.

 

D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}

Then

D2 is {'A':6, 'B': 15}


View Solution


Program [15]

A dictionary has three keys: 'assets', 'liabilities' and 'capital'. Each of these keys store their value in form of a list storing various values of 'assets', liabilities' and 'capital' respectively. Write a program to create a dictionary in this form and print. Also test if the accounting equation holds true.


View Solution


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad