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.

Qus What do you understand by mutability?

Ans: Mutable means changeable. In Python, mutable types are those whose values can be changed in place. Only three types are mutable in python – Lists, Dictionaries and Sets.

Qus Start with the list[8,9,10]. Do the following using list functions

(a) Set the second entry (index 1) to 17

(b) Add 4, 5 and 6 to the end of the list.

(c) Remove the first entry from the list.

(d) Sort the list.

(e) Double the list.

(f) Insert 25 at index 3


Ans:

(a) list[1]=17

(b) list.append(4)

list.append(5)

list.append(6)

(c) list.pop(0)

(d) list.sort()

(e) list=list*2

(f) list.insert(3,25)


Qus.  If a is [1, 2, 3], what is the difference (if any) between a*3 and [a, a, a]?

Ans: a*3 will produce [1,2,3,1,2,3,1,2,3], means a list of integers and [a, a, a] will produce [[1,2,3],[1,2,3],[1,2,3]], means list of lists


Qus. If a is [1, 2, 3], is a *3 equivalent to a + a + a?

Ans: Yes, Both a*3 and a+a+a will produce same result.


Qus. If a is [1, 2, 3], what is the meaning of a [1:1] = 9?

Ans: This will generate an error "TypeError: can only assign an iterable'.


Qus If a is [1, 2, 3], what is the meaning of a [1:2] = 4 and a [1:1] = 4?

Ans: These will generate an error "TypeError: can only assign an iterable".

Qus. What are list slices?

Ans: List slices are the sub-part of a list extracted out. You can use indexes of the list elements to create list slices as per following format. Syntax is as follows –

Qus Does a slice operator always produce a new list?

Ans: Yes, this will create a new list.


Qus. How are lists different from strings when both are sequences?

Ans: Lists are similar to strings in many ways like indexing, slicing, and accessing individual elements but they are different in the sense that

(i) Lists are mutable while strings are immutable.

(ii) In consecutive locations, strings store the individual characters while list stores the references of its elements.

(iii) Strings store single type of elements-all characters while lists can store elements belonging to different types.


Qus. What are nested Lists?

Ans: A list can have an element in it, which itself is a list. Such a list is called nested list. e.g.

L = [1,2,3,4,[5,6,7],8]


Qus. Discuss the utility and significance of Lists.

Ans: The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. List is majorly used with dictionaries when there is large number of data.


Qus What is the purpose of the del operator and pop method? Try deleting a slice.

Ans: del operator is used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below –

>>>del List[index]

>>>del List[start:stop]

pop method is used to remove single element, not list slices. The pop() method removes an individual item and returns it. Its syntax is –

>>>a=List.pop() #this will remove last item and deleted item will be assigned to a.

>>>a=List[10] # this will remove the ite at index 10 and deleted item will be assigned to a.


Qus. What are list slices?

Ans: List slices, like string slices are the sub part of a list extracted out. Indexes can be used to create list slices as per following format:

seq = L[start:stop]


Qus. What do you understand by true copy of a list? How is it different from shallow copy?

Ans: A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won‘t create copies of the child objects themselves.

True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.


Qus What do you understand by immutability?

Ans: Immutability means not changeable. The immutable types are those that can never change their value in place. In python following types are immutable –

I. Integers

II. Floating point numbers

III. Booleans

IV. Strings

V. Tuples


Qus How are Tuples different from Lists when both are sequences?

Ans: Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but they are different in the sense that –

Tuples are immutable while lists are mutable.

List can grow or shrink while tuples cannot.


Qus Can tuples be nested?

Ans: Yes, tuples can be nested. e.g (1,2,3,(4,5,6))


Qus. Discuss the utility and significance of Tuples.

Ans: Tuples are great for holding static data that you don't plan on modifying and changing a lot. Tuples are four to seven times faster than lists. This means for every list item manipulated, four to seven tuples could be manipulated within that time frame. This has huge advantages for scientific work, as this allows for speedy data reading.


Qus. How can you say that a tuple is an ordered list of objects?

Ans: A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index amd for a given index, same element is returned every time.


Qus. Why can‟t List can be used as keys?

Ans: List is mutable datatype. And Keys of dictionary must be immutable type. This is the region that list cannot be used as keys.


Qus. What type of objects can be used as keys in dictionary?

Ans: Any immutable objects can be used as keys in dictionary.


Qus. Can you change the order of the dictionaries contents?

Ans: Yes, the order of dictionary contents may be changed.


Qus. Can you modify the keys in a dictionary?

Ans: Keys cannot be modified in dictionary while values are mutable in dictionary.


Qus. Can you modify the value in a dictionary?

Ans: Yes, Values can be modified in dictionaries.


Qus. Is dictionary Mutable? Why?

Ans: Dictionary is mutable type because we can change its values.


Qus How are dictionaries different from Lists?

Ans: The dictionary is similar to lists in the sense that it is also a collection of data-items but it is different from lists in the sense that lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered).

Elements in lists or tuples can be accessed by using indexes. But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list.


Qus. When are dictionaries more useful than lists?

Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.


Qus. Discuss the utility and significance of Dictionaries.

Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.


Qus. Why is a dictionary termed as an unordered collection of objects?

Ans: But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list. In dictionaries there is no index. It uses its keys as index which can be rearranged. That‘s why a dictionary termed as an unordered collection of objects


Qus. How is clear() function different from del <dict> Statement?

Ans: clear() removes all the elements of a dictionary and makes it empty dictionary while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no longer exists, not even empty dictionary.


Programs

WAP to find the 2nd largest number from the list of the numbers entered through keyboard.


View Solution


Write a python program that creates a list of numbers from 1 to 20 that are divisible by 4


View Solution


Write a python program to define a list of countries that are a member of BRICS. Check whether a county is member of BRICS or not


View Solution


Python program to read marks of six subjects and to print the marks scored in each subject and show the total marks


View Solution


Python program to read prices of 5 items in a list and then display sum of all the prices, product of all the prices and find the average


View Solution


Python program to count the number of employees earning more than 1 lakh per annum. The monthly salaries of n number of employees are given


View Solution


Write a program to create a list of numbers in the range 1 to 10. Then delete all the even numbers from the list and print the final list.


View Solution


Write a program to generate in the Fibonacci series and store it in a list. Then find the sum of all values.


View Solution


Write a program to swap two values using tuple assignment


View Solution


Write a python program using a function that returns the area and circumference of a circle whose radius is passed as an argument.two values using tuple assignment


View Solution


Write a program that has a list of positive and negative numbers. Create a new tuple that has only positive numbers from the list


View Solution


Python Program that generate a set of prime numbers and another set of even numbers. Demonstrate the result of union, intersection, difference and symmetirc difference operations.


View Solution


WAP to find minimum element from a list of elements along with its index in the list.


View Solution


WAP to calculate mean of a given list of numbers.


View Solution


WAP to search for an element in a given list of numbers.


View Solution


WAP to count frequency of a given element in a list of numbers.


View Solution


WAP to calculate the sum of integers of the list


View Solution


WAP that reverses an array of integers (in place)


View Solution


WAP that creates a third list after adding two lists.


View Solution


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


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


View Solution