Python Tutorial: Dictionary Unsolved Questions (Preeti Arora)

Friday, 24 December 2021

Dictionary Unsolved Questions (Preeti Arora)

 Q1. What is a key-value pair in dictionary?

Solution:-

Dictionaries are simply another type of collection in Python, but with a twist. Rather than having an index associated with each data-item (just like in lists or strings), Dictionaries in Python have a "key" and a "value of that key". That is, Python dictionaries are a collection of some key-value pairs.
For example:-
Just like in English dictionaries you can search for a word's meaning, because for each word, there is a meaning associated with it. In the same manner, Python dictionaries have some keys (just like English dictionaries have words) and associated values (just like English dictionaries have associated meanings for every word).
• Dictionaries are containers that associate keys to values. This is, in a way, similar to lists. In lists, you must remember the index value of an element from the list, but with the case of dictionaries, you'll have to know the key to find the element in the dictionaries.

Q2. What are the differences between strings and dictionary?

Solution:-

The dictionary is similar to string in the sense that it is also a collection of data-items just like string BUT it is different from string in the sense that string are sequential collections (ordered) and dictionaries are non-sequential collections (unordered).
In string, where there is an order associated with the data-items because they act as storage units for other objects or variables you've created. Dictionaries are different from string, lists and tuples because the group of objects they hold aren't in any particular order, but rather each object has its own unique name, commonly known as a key.

Q3. Find errors and rewrite the same after correcting the following code:

(a) d1 = {1:10, 2.5:20, 3:30, 4:40, 5:50, 6:60, 7,70}

(b) d1 (9)=90

(c) del d1 (2)

(d) pop d1 [4]

(e) d1.item ()

(f) d1.key()

(g) d1.value ()

(h) d1.gets (4,80)

(i) d1.len ()

(j) d1.clears ()

Solution :-
a = d1 = {1:10, 2.5:20, 3:30, 4:40, 5:50, 6:60, 7:70}
b = d1 [9]=90
c = del d1 [2.5]
d = d1.pop(4)
e = d1.items()
f = d1.keys()
g = d1.values()
h = d1.get(4,80)
i = len(d1)
j = d1.clear()

Q4. Suppose

>>>d1 = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}

>>>d2 = {5: 'five', 6: 'six'}

Write the output of the following code:

(a)

>>>d1.items ()

>>>d1.keys ()

>>>d1.values ()

>>>d1.update (d2)

>>>len (d1)

(b)

>>>del d1[3]

>>>print (d1)

>>>d1.pop (4)

>>>print (d1)

>>>d1 [8] = 'eight'

>>>print (d1)

>>>d1.clear ()

>>>print (d1)

Solution :-
(a)
>>> d1.items ()
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
>>> d1.keys ()
dict_keys([1, 2, 3, 4])
>>> d1.values ()
dict_values(['one', 'two', 'three', 'four'])
>>> d1.update (d2)
>>> len (d1)
(b)
>>> del d1[3]
>>> print (d1)
{1: 'one', 2: 'two', 4: 'four', 5: 'five', 6: 'six'}
>>> d1.pop (4)
'four'
>>> print (d1)
{1: 'one', 2: 'two', 5: 'five', 6: 'six'}
>>> d1 [8] = 'eight'
>>> print (d1)
{1: 'one', 2: 'two', 5: 'five', 6: 'six', 8: 'eight'}
>>> d1.clear ()
>>> print (d1)
{}

Q5. Write a program to input ‘n’ classes and names of their class teachers to store them in a dictionary and display the same. Also accept a particular class from the user and display the name of the class teacher of that class.

Solution :

dic = {}

while True :

    clas = int(input("Enter class :-"))

    teach = input("Enter class teacher name :-")

    dic[clas]= teach

    a = input("Do you want to enter more records enter (Yes/ No)")

    if a == "No" or a == "no":

        break

clas = int(input("Enter class which you want to search"))

print("class teacher name",dic[clas])

 

Q6. Write a program to store student names and their percentage in a dictionary and delete a particular student name from the dictionary. Also display the dictionary after deletion.

 

Solution : 

dic = {}

while True :

    nam = input("Enter name :-")

    per = float(input("Enter percentage :-"))

    dic[nam] = per

    a = input("Do you want to enter more records enter (Y/ N)")

    if a == "N" or a == "n":

        break

 

clas = input("Enter name which you want to delete :-")

del dic[clas]

print("Dictionary",dic)

 

Q8. Write a Python program to input names of 'n' customers and their details like items bought, cost and phone number, etc., store them in a dictionary and display all the details in a tabular form.

 

Solution :

dic = {}
while True :
    nam = input("Enter name :-")
    phone = float(input("Enter phone number :-"))
    cost = float(input("Enter cost :-"))
    item = input("Enter item :-")
    dic[ nam ] = [ phone , item , cost ]
    a = input("Do you want to enter more records enter (Yes/ No) :- ")
    if a == "No" or a == "no":
        break
 
for i in dic :
    print()
    print("Name : " i )
    print("Phone : ", dic[ i ][ 0 ] , "\t", "Cost : ", dic[ i ][ 1 ] , "\t", "Item : ", dic[ i ][ 2 ])

Q9. What type of objects can be used as keys in dictionaries?

Solution :
Immutable type of object can be used in dictionary.
Example - integers, string, tuple

Q10. Can you check for a value inside a dictionary using in operator? How will you check for a value inside a dictionary using in operator?

Solution :

Yes we can check for a value inside a dictionary using in operator
Syntax :-
<Value> in dic.value ()

Q11. How is clear( ) function different from del <dict> statement?

Solution :
clear () function delete the all keys and values in the dictionary and leave the dictionary empty.
While del <dict> delete the complete dictionary when we want to find deleted dictionary then it will give error that <dict> not defined.

Q12. The following code is giving some error. Find out the error and write the corrected code.


d1 = {“a":1, 1:"a", [1, "a"]:"two"}

Solution:-
Data type of key is never list.
So, [1, "a"] is wrong.

Q13. What will be the output of the following code:

d1 = {5: [6, 7, 8], "a": (1, 2, 3)}

print (d1.keys ())

print (d1.values())

Solution :-
dict_keys([5, 'a'])
dict_values([[6, 7, 8], (1, 2, 3)])

>>>

Q14. Predict the output:

(a)

d = {(1, 2):1, (2, 3):2}

print (d[1, 2])


(b)

d = {'a': 1, 'b':2, 'c':3}

print (d['a', 'b'])


Solution :-
(a) 1
(b) It will give error because d['a', 'b'] will take only one argument.

 

Q16. Consider the following dictionary stateCapital:

stateCapital = {"Assam" : "Guwahati", "Rajasthan":"Jaipur", "Bihar": "Patna", "Maharashtra": "Mumbai","Rajasthan":"Jaipur"}

Find the output of the following statements:

(a) print (stateCapital.get ("Bihar"))

(b) print (stateCapital.keys ())

(c) print (stateCapital.values())

(d) print (stateCapital.items())

(e) print (len (stateCapital))

(f) print ("Maharashtra" in stateCapital) (g) print (stateCapital.get ("Assam") )

(h) del stateCapital ["Assam"]

print (stateCapital)

Solution :

(a) Patna

(b) dict_keys(['Assam', 'Rajasthan', 'Bihar', 'Maharashtra'])

(c) dict_values(['Guwahati', 'Jaipur', 'Patna', 'Mumbai'])

(d) dict_items([('Assam', 'Guwahati'), ('Rajasthan', 'Jaipur'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai')])

(e) 4

(f) True

(g) Guwahati

(h) {'Rajasthan': 'Jaipur', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}

Q17. 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.

Solution :

dic = { }

 

while True :

    product = input("enter the name of product (enter q for quit )= ")

    if product == "q" or product == "Q" :

        break

    else :

        price = int(input("enter the price of product = "))

        dic [ product ] = price

 

while True :

    name = input("enter the name of product those you are entered (enter q for quit )= ")

    if name == "q" or name == "Q" :

        break

    else :

        if name not in dic :

            print("name of product is invaild")

        else :

            print("price of product = ",dic[name])

 

Q18. Write a Python program that accepts a value and checks whether the inputted value is part of given dictionary or not. If it is present, check for the frequency of its occurrence and print the corresponding key otherwise print an error message.

Solution :-

dic = eval(input("Enter a dictionary :- "))

val = eval(input("Enter a value :-")) 

lst = list( dic.values() )

if val in lst :

    print("Frequency of occurrence of ",val ," is ", lst.count( val ))

    print("Its key are :-" )

    for i in dic :

        if dic [i] == val :

            print(i)

else :

    print("Not found !!")

Output :-
Enter a dictionary :- {1:10, 2.5:20, 3:30, 4:40, 5:50, 5.5 : 50 , 6:60, 7:70}
Enter a value :-50
Frequency of occurrence of  50  is  2
Its key are :-
5
5.5

>>>


No comments:

Post a Comment