Dictionary and Tuples

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

die ionary in Python is a

collection of
Ad
all mutable values are
unordered values which
he types

and tuples are not. compound types. Lists and are accessed by keys.
g s

which
dictionaries are mutable, while
move
tors which move
characters the cursor
Any without printing visible characters
clear() method removes all items
from the called whitespace.
are called
ihe
The get() meti method returns a Value tor the dictionary. whitespace
given key. If key is not
value None.
available then it returns detauit
The item() method returns a list of the
ne key)method returns a list of the dictionary's key-value pairs.
alue) method returns a list of thedictionary' s keys.
7
The

dictionary's values.
IDdate() methd adds dictionary contentsinto
function does not return anything, another dictionary's key-value pairs. This

unles are
Tuples are a type of
ot sequence like
strings. But unlike
tupies can contain elements of any type. strings, which can only contain characters,
The len() function returns the number of elements in the
tuple.
The tuple functions max() and min() find the maximum and
minimum value in a sequence of values.

SoLVED EXERCISES
1. What is a dictionary?
Ans. A Python dictionary is a group of key-value pairs. The elements in a dictionary are indexed by keys.
Keys in a dictionary are required to be unique.
2. How can you access data from a dictionary?
Ars. The simplest way to retrieve a value from a dictionary is by directly accessing it with a key. To get a
key's value, just put the key in brackets, following the name of the dictionary.
3. What does the item() method of dictionary return?
Ans. The items() method returns a list of dictionaries (key: value) pairs as tuples.
4. What is the main of
use a dictionary?
Ans. The main use of a dictionary is to look up the value associated with a particular key.

.WhyPython dictionaries are called mappings?


Ans
AnS.
Python dictionaries are called mappings because these are like a collection that allows us to look up
intormation associated with arbitrary keys.
.
Define update() method.
328 Sanasmatt Computer
Ans. Theupdate() method updates the dictionary with the key-value pairs in the other
dictin. A Science
current values. Alternatively, update can be invoked with ionary replacing
keyword parameters resultin
corresponding pairs in the dictionary being updated.
7. Define tuple. the
Ans. A tuple is an immutable list. A tuple cannot be
changed in any way once it is
created. Tuples s
in
parentheses instead of square brackets. Since tuples
any ofitems
are immutable, we cannot replace ce coded
8. Differentiate between list and tuples.
Ans. The differences are:
List are mutable while
tuples are not.
Tuples can be hashed e.g., to be used as
Tuples used when the order of the keys
for dictionaries while list
are are not.
9. Write a program to take the elements in the sequence matters.
number of students as
Physics,'Chemistry', input,
'Maths' and 'Computer. If the
then ask marks for five
then print he failed or else total marks for any subjects as 'Enelic
print passed. Use a student are less
than 200
as values. to dictionary store the student name
as key and
Ans. #File marks
name:.. \MyPythonXI\PyChap15
n
int(input("Enter the PStudent.py
number of students:"))
data =
{}# here we will store the data
languages (English', Physics,
=

for i in range(0, 'chemistry, 'Maths',


n): #for the n number of students 'Computer) #all languages
#Get the name of the
student
name =

input('Enter the name of the student %d: '%


marks [1 (i+1))
for x in
languages:
#Get the marks for
languages
marks.append(intinput('Enter
dataname] =marks
marks of %s: %
'

x))
for x, y in
data.items():
total = sum(y)
print ("%s 's total marks %d" % (x,
if total < 200: total))
print ("%s failed" % x)
else:
print ("%s passed)" %
10. Write a y)
program to input
information in ascendingemployee number and name for
order of their 'N'
employee number. employees and display all emp oyee's
Ans. # File
name:
#
Searching customer name with
Emp } # An
. \ MyPythonXI\PyChap15\Eorder.py respective phone number
empty dictionary
#Function to append employee
def EmployeeDict(Emp): number and name
Ch 'Y
while Ch ==
'Y' or Ch ==
"YES':
print ("Enter
ENo = input() employee no.: "

, end="")
print ("Enter name: "

, end="")
sing with Dictionaries and Tuples
WorkA

EName =input() 329


Emp[ENo] = EName

orint ("Add more


employee <y/n>: ", end=""
Ch input().upper()
if Ch == 'N' or Ch == 'NO':

break
HAdding employee into dictionary
EmployeeDict(Emp)
EKey Emp.keys()
Elist = list(EKey) # Converts keys into a list
Flist.sort() #Employee nos. arearranged in ascending order
print()
print ("Employee list...")
print ( " " * 40)

orint ("(0:<25} {1:>12}". format("Employee No.", "Name"))


print ( " " * 40)

for i in EList:

print ("(0:<25} {1:>12}".format(i, Emp[i]))


print ( " " * 40)

11. Write a program to enter 'N numbers in a tuple Num and find the sum, maximum and minimum
values in the tuple.
Ans. # File name: ...\\MyPythonXI\PyChap15\TSum.py
# Program to find sum, max and min in a tuple
Num tuple() #An empty tuple
print ("How many numbers you want to enter: ", end=")
N = int(input())
Ctr 1
ifN>0:
while Ctr<= N:
print ("Enter No.:", Ctr, end="
-> ")
Val =intfinput())
Num += (Val,)
Ctr+= 1
print ("Tuple is:", Num)
print ("Total =", sum(Num))
print ("Maximum =", max(Num))
print ("Minimum =", min(Num)) will randomly pick a word from a
12. Write aa where computer
word jumble game
program for if it is correct, then print an
se
e should guess a
word from the tuple,
uence (tuple). The user
as follows:
appropriate messa The tuple is given "MySql", "Fortran")
"Cobol", "C++", "Java", "Visual Studio",
Ans File dme:..("Python",
Ans. #RDS= \MyPythonXI\PyChap15Vgame.py
#Word Jumble game
import random
cre choose from
Sequence of words to "MySql", "Fortran")
d "C++", "Java", "Visual Studio",
("Python", "Cobol",
330 Sarasavatl Computer Sci
#pick one word randomly from the sequence
science n
word random.choice(WORDS)
#Create a variable to use later to see ifthe guess is correct
correct= word
correct correct.lower()
#create a jumbled version of the word
jumble =""

while word:
position random.randrange(len(word))
jumble + word[position]
word =
word[:position] word[(position+1):]
+
#start the game
print

t tWelcome to Word Jumble Game!


t\t
\tUnscramble the letters to make a word.
(Note. Press the enter key at the prompt to quit.)

print ("The jumble word is:", jumble)


guess input("\nPlease enter again your guess: ")
=

while (guess != correct) and (guess !=


"):
print ("Sorry, %s is not exactly the jumble word" %jumble)
guess input("Please enter again your guess: ")
=

guess guess.lower()
if guess == correct:

print ("That's it! You guessed it!\n")


print ("Thanks for playing.")
13. Write a menu driven program to input scores for
to their
players and display the details of scores according
highest score. The menu is as:
0 Quit
1 Add a Score
2- List Scores
Ans. # File
# Menu drive
name:.\\MyPythonXI\PyChap15\hscore.py
program to list players scores,
# Also print the total score
input scores, and find total scores.
while listing the scores.
scores [
choice None
while choice != "0":
print ("High Scores Keeper")
print ("0 - Quit")

print ("1 Add a Score")


print ("2 List Scores\n")
choice
input("Choice: ")
=

print()
#exit
and Tuples
y a l w i t hD
th
Dictionaries 331
= =
"O"
choice

f print ("Good-bye.")

sCore

a
ddd
4 == "1":
choice

elit name = input("What is the player's name?: ")


ore = input("What score did the player get?: "))
= (score, name)
entry
scores.append(entry)

scores.sort()

scores.reversel) # want the highest number first


high-score table
# display
choice
== "2":
elif
tscore 0
> 0:
if len(scores)
print ("NAME\t\tSCORE")

for entry in scores:

Score, name = entry

tscore = tscore + score

print (name, "\t\t", score)


print ("Total score is:", tscore)
print
else:
print ("The list empty")
is
option 2.")
print ("Please try
#some unknown choice

else: valid choice.")


choice, "isn't a
print ("Sorry, but",

REVIEW QUESTIONS
declare a dictionary.
we can
Write the methods by which example.
with an
dictionary? Explain
L.Can you modify a
allowed)
3.Whatare the dictionary keys?
answers
dictionary?(multiple

statements
create a

wnich of the following


a) d= {
(b) d ("Amit":15, "Rakesh":16}
C d {15:"Amit", 16:"Rakesh")
=

d) d (15:"Amit", 16:"Rakesh") code?


following Python
.What will be the output of the
d1 ("Amit":14, "Rakesh":16}
02{"Amit":155, "Rakesh":16)
d1== d2 code?
following Python
What will be the output of the
ADict = (1:100, 200, 3:300, 4:400, 5:500
print (ADict.items)
332
Sanasm Computer Sciene
print (ADict.keys())
print (ADict.values())
What will be the output of the following Python code?
bcience
ATuple ('p', 'q', 'r', 'P', 'Q', 'R', 'W')
max (ATuple)
min (ATuple)
8. Create dictionary called Product containing
program to perform the ProdID, ProdName and Price.
following: Write a
Add product.
menu driven
Modify product.
3. Delete product.
4. Display details in
ascending order and
5. Exit
Write a
program to create
functions, perform the
a
dictionary called Census with
following: Country name and
Search_Country()- Enter the country name and Population, Ueine
Delete_Country()
Display Enter the country name and
display its respective
delete population.
appropriate message if the country is not
its
respective population.
found in the dictionary.

You might also like