0% found this document useful (0 votes)
398 views

String Lists Tuples Dictionaries: Module-2

The document discusses strings, lists, tuples and dictionaries in Python. It provides details about strings such as how they are immutable sequences of characters that can be indexed and sliced. It also discusses creating and accessing lists, nested lists, negative indexing and mixed data types in lists. Various string methods like find, split, replace, upper and lower are also explained along with examples.

Uploaded by

harsha sid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
398 views

String Lists Tuples Dictionaries: Module-2

The document discusses strings, lists, tuples and dictionaries in Python. It provides details about strings such as how they are immutable sequences of characters that can be indexed and sliced. It also discusses creating and accessing lists, nested lists, negative indexing and mixed data types in lists. Various string methods like find, split, replace, upper and lower are also explained along with examples.

Uploaded by

harsha sid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 166

Module-2

String
Lists
Tuples
Dictionaries
 
String
A string is a sequence of characters.
String pythons are immutable.
We can simply create Python String by enclosing a text in single as well as
double quotes. Python treat both single and double quotes statements same.
A character is simply a symbol. For example, the English language has 26
characters.
Computers do not deal with characters, they deal with numbers (binary).
Even though you may see characters on your screen, internally it is stored
and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse
process is decoding. ASCII and Unicode are some of the popular encoding
used.
How to create a string in Python?
my_string = 'Hello’
print(my_string)

my_string = "Hello”
print(my_string)

my_string = '''Hello’’’
print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python""“
print(my_string)

3
If we want to print a text like - He said, "What's there?“

This will result into SyntaxError as the text itself contains both
single and double quotes.

print("He said, "What's there?"")

4
Common escape sequences
Sequence Meaning

\\ literal backslash
\' single quote
\" double quote
\n newline
\t tab

5
Python String Formatting
One way to get around this problem is to use triple quotes.
Alternatively, we can use escape sequences.
# using triple quotes
print('''He said, "What's there?“ ''')
# escaping single quotes
print('He said, "What\'s there?"')
# escaping double quotes
print("He said, \"What's there?\"")

6
Accessing Strings:
In Python, Strings are stored as individual characters in a contiguous
memory location.
The benefit of using String is that it can be accessed from both the
directions in forward and backward.
Both forward as well as backward indexing are provided using Strings in
Python.
Forward indexing starts with 0,1,2,3,....
Backward indexing starts with -1,-2,-3,-4,....

7
How to access characters in a string?
• We can access individual characters using indexing and a
range of characters using slicing. Index starts from 0.
• Trying to access a character out of index range will raise an
IndexError. The index must be an integer. We can't use float
or other types, this will result into TypeError.
• Python allows negative indexing for its sequences.

8
String slicing
Example

x = "Welcome to Python“ Output:


print (x[2:5]) lco
print (x[:]) Welcome to Python
print(x[0:]) Welcome to Python
print(x[0:len(x)]) Welcome to Python
print(x[4:10:2]) oet
print(x[-5:-3]) yt
print(x[ : :-1]) nohtyP ot emocleW

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
W e l c o m e t o P y t h o n
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

9
How to change or delete a string?
• Strings are immutable. This means that elements of a string
cannot be changed once it has been assigned.
• We can simply reassign different strings to the same name.
• We cannot delete or remove characters from a string. But
deleting the string entirely is possible using the keyword del.
my_string = 'programiz'
my_string[5] = ‘e'
TypeError: 'str' object does not support item assignment
my_string = 'Python'

10
Operators to work with strings

11
Concatenation of strings
Length of a String s1 = "Core"
str = "Core Python" s2 = "Python"
print(s1 + s2)
n = len(str)
print("Len: ", n)

Membership Operators
str = input("Enter the first string: ")
Repeating the strings sub = input("Enter the second string: ")
str = "Core Python" if sub in str:
print(str * 2) print(sub +" is found in main string")
else:
print(sub+" is not found in main string")
Methods for the str object

13
string.find(value, start, end)

Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of
the string

14
find()
strip(), lstrip(), rstrip()
txt = "Hello, welcome to my world.“ output:
txt = ",.banan.."
print(txt.find("welcome")) 7 print(txt.strip(',.'))
print(txt.find("e")) 8 print(txt.lstrip())
print(txt.find("e",5, 10)) 1 print(txt.rstrip())

count()
txt = "I apple love banana,apples are my favorite fruit"
x = txt.count("apple",10,27)
print(x)

o/p: 1
string.split(separator, maxsplit)

txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)

o/p: ['apple', 'banana#cherry#orange']

16
replace() rfind()
txt = "one one was a race horse, two two was one too." txt = "Mi casa, su casa."
print(txt.replace("one", "three",2)) x = txt.rfind("casa")
print(x)

startswith(), endswith() title()


txt = "Hello, welcome to my world." txt = "Welcome to my 2nd world"
print(txt.startswith("Hello",6,12)) print(txt.title())
print(txt.endswith("Hello"))
Methods for the str object
num="123“
name="india is mycountry“
print(name.isupper())
print(name.islower())
print(name.upper())
print(name.find("123"))
print(name.isalnum())
print(name.isalpha())
print(name.split())
print(num.isdecimal())
Finding the Sub-Strings
str = input("Enter the main string:")
sub = input("Enter the sub string:")
#Search for the sub-string
n = str.find(sub, 0, len(str))
if n == -1:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Write a program to print every character of a string entered by user in a
new line using loop

test=input("Enter the string:")


for i in test:
print(i)
Write a program to check if the letter 'e' is
present in the word 'Umbrella'.
test="Umbrella“
if "e" in test:
print("Yes")
else:
print("No")
Write a program that takes your full name as input and displays the abbreviations of
the first and middle names except the last name which is displayed as it is. For
example, if your name is Robert Brett Roser, then the output should be R.B.Roser
test=input("Enter the full name")
test=test.split()
print(test[0][0],".",test[1][0],test[2])
Program to count vowels, consonant, digits and special characters in string.
vowels ,consonant ,specialChar,digit= 0,0,0,0
test="india is my country“
for i in range(0, len(test)):
ch = test[i]
if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') ):
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch >= '0' and ch <= '9'):
digit += 1
else: specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit) print("Special Character:", specialChar)
Ask the user to input a string which contains at-least 4 words. Capitalize
first letter of each word and display output by merging all capital letters
in the string.
Example:
input: “So many books, so little time”
Output:SMBSLT
s=input()
a=s.title()
newstring="“
for i in a:
if i.isupper():
newstring+=i
print(newstring)
LISTS
• Is a mutable data structure
• Linear with variable length
• Values are separated by a comma within
square brackets
• Can have mixed data types
• A list can have another list as an item
• Ex: [1, 2, 3] [‘one’, ‘two’, ‘three’]
[‘apples’, 50, True] [‘mouse’,
[1,2,3]]

28
Accessing a list
• Elements are accessed using the index operator [ ]
• Index starting from 0, must be integer
• Index error - Accessing an element out of range
• TypeError – index is not an integer.
• Nested lists are accessed using nested indexing
• >>> n_list = ["Happy", [2,0,1,5]]
• >>> n_list[0][1] # nested indexing
• 'a'
• >>> n_list[1][3] # nested indexing
• 5

29
Negative Indexing
• Sequences(lists, tuples and strings) can have
negative indexing
• Index -1 refers to the last item, -2 refers to second
last and so on.
• >>> my_list = ['p', 'r', 'o', 'b', 'e']
• >>> my_list[-1]
• 'e'

30
List Slicing
• A range of elements in a list can be accessed using
the slicing operator : and two indexes from where
the portion of the list has to be sliced
• >>> my_list = ['p','r','o','g','r','a','m','i','z']
• >>> my_list[2:5] # elements 3rd to 5th
• ['o', 'g', 'r']
• >>> my_list[:-5] #elements beginning to 4th
• ['p', 'r', 'o', 'g']

31
List Slicing….
• >>> my_list[5:] # elements 6th position to
end
• ['a', 'm', 'i', 'z']
• >>> my_list[:] # elements beginning to end
• ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

32
List Slicing….
• A slice operator on the left can update multiple
elements
• >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
• >>> t[1:3] = ['x', 'y']
• >>> print t
• ['a', 'x', 'y', 'd', 'e', 'f']

33
Changing elements in a list
• = assignment operator is used to modify an item or a range of items in a list
• >>> odd = [2, 4, 6, 8] # mistake values
• >>> odd[0] = 1 # change the 1st item
• >>> odd
• [1, 4, 6, 8]

• >>> odd[1:4] = [3, 5, 7]


• >>> odd # changed values
• [1, 3, 5, 7]
1
2
3

34
Adding elements to a list
• append() – used to add an item to a list
• extend() – used to add multiple items to a list
• >>> odd = [1, 3, 5]
• >>> odd.append(7)
• >>> odd
• [1, 3, 5, 7]
• >>> odd.extend([9, 11, 13])
• >>> odd
• [1, 3, 5, 7, 9, 11, 13]
• The + operator is used to concatenate two lists
• The * operator is used to repeat a list for a given number of
times
• >>> odd
• [1, 3, 5]
• >>> odd + [9, 7, 5]
• [1, 3, 5, 9, 7, 5]
• >>> ["re"] * 3
• ['re', 're', 're']
Insertion into a list
• insert() – used to insert an item/items at a desired
location
• >>> odd = [1, 9]
• >>> odd.insert(1,3)
• >>> odd
• [1, 3, 9]
• >>> odd[2:2] = [5, 7]
• >>> odd
• [1, 3, 5, 7, 9]
Deleting from a list
• del is used to delete one/more/entire list
• my_list = ['p','r','o','b','l','e','m']
del my_list[2] # delete one item
print(my_list)
o/p: ['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5] # delete multiple items
print(my_list)
o/p: ['p', 'm']
del my_list # delete entire list
print(my_list)
... NameError : my_list is not defined.
Deleting from a list
• Remove() – used to remove the first matching
given item

• my_list = ['p','r','o','b','l','e','m']
• >>> my_list.remove('p')
• >>> my_list
• ['r', 'o', 'b', 'l', 'e', 'm']
Deleting from a list
• Pop() – used to remove an item at a given index
>>my_list = ['r', 'o', 'b', 'l', 'e', 'm']
>>> my_list.pop(1)
'o'
>>> my_list
['r', 'b', 'l', 'e', 'm']
Deleting from a list
• Clear() – used to empty a list
my_list = ['r', 'b', 'l', 'e']
my_list.clear()
print(my_list)
o/p: []
Deleting from a list
• A list can also be deleted by assigning an empty list to
a slice of elements
• >>> my_list = ['p','r','o','b','l','e','m']
• >>> my_list[2:3] = []
• >>> my_list
• ['p', 'r', 'b', 'l', 'e', 'm']
• >>> my_list[2:5] = []
• >>> my_list
• ['p', 'r', ‘e’, 'm']
ITERATING OVER LISTS (SEQUENCES)

• Using for to iterate over a list


• Ex 1:
for k in [4,3,2,1]:
print (k)
???????
• Ex 2:
for k in [‘Apple’, ‘Banana’, ‘Pear’]
print (k)
?????????
ITERATING OVER LISTS (SEQUENCES)

• Ex 3:
for k in ‘apple’:
print (k)
???????
• Ex 4:
for k in range(0,11):
print (k)
??????
ITERATING OVER LISTS (SEQUENCES)

• Ex 5:
for k in range(2,10,2):
print (k)
???????
• Ex 6:
for k in range(10,-1,-2):
print (k)
??????
Exercise Programs
Pgm. 1

# find the sum of all numbers stored in a list


nums = [1,2,3,4,5]
sum = 0
for i in range(0,len(nums)):
sum = sum + nums[i]
 
print('Sum =', sum)
Pgm 2
# find the sum of all numbers stored in a list

nums = [1,2,3,4,5]

sum = 0
for n in nums:
sum = sum + n
 
print('Sum =', sum)
Pgm 3
# find the sum and average of all n numbers stored
in a list given by the user.
 sum = 0
marks = [] #initialize empty list
size = int(input('Enter size of the list'))
print('Size of the list is', size)
 
for i in range(0,size):
a= int(input('Enter a number'))
marks.append(a)
for x in marks:
print('Element is', x)
sum = sum + (x)

print('Sum =', sum)


print('Average =', sum/float(size))
Pgm. 4
#Read a list of integers. From the input list, store only integers #
between 1 and 100 in another list.
 
list1 = []
list2 = []
 
size = int(input('Enter size of the list'))
 
for i in range(size):
num = int(input('Enter a number'))
list1.append(num)

print('The input list is‘, list1)


Pgm. 4…..
for i in list1:
if i>=1 and i<=100:
list2.append(i)
 
print('The new list is ‘, list2)
Pgm 5
# Read the ages of a list of people into a list. For all ages between 40
to 50, # the string ‘middle age’ should be stored instead. Print the
resulting list.
 
ages = []
nop = int(input('Enter the total no. of people'))
 
for i in range(nop):
a = int(input('Enter an age'))
ages.append(a)
 
print('\nThe Input Ages Are:\n')
for i in ages:
print(i)
 
Pgm 5…..
for i in range(len(ages)):
if ages[i]>40 and ages[i]<50:
ages[i] = 'middle age'
 
 
print('\nThe Modified Ages Are:\n')
for i in ages:
print(i)
List Methods in Python
• >>> my_list = [3, 8, 1, 6, 0, 8, 4]
• >>> my_list.index(8)
•1
• >>> my_list.count(8)
•2
• >>> my_list.sort()
• >>> my_list
• [0, 1, 3, 4, 6, 8, 8]
• >>> my_list.reverse()
• >>> my_list
• [8, 8, 6, 4, 3, 1, 0]
Sorting a list

• The sort() method sorts the list ascending by default.


• cars = ['Ford', 'BMW', ‘Bolvo']
cars.sort(reverse=True)
Syntax:
list.sort(reverse=True|False, key=myFunc)

• reverse - If TRUE, the sorted list is reversed (or sorted in


Descending order)

• key - function that serves as a key for the sort comparison

55
• The sorted() function returns a sorted list of the specified
iterable object.

• You can specify ascending or descending order. Strings are


sorted alphabetically, and numbers are sorted numerically.

sorted(iterable, key=key, reverse=True/False)

• a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)

56
Assigning and Copying Lists
• A list can be assigned or copied to another list using
the assignment operator =.
• >>>list1 = [10,20,30,40]
• >>>list2 = list1
• >>>list1[0] = 5
• >>>list1
• [5,20,30,40] #change made in list1
• >>>list2
• [5,20,30,40] # change in list1 causes a change in list2
list1 = [10,20,30,40]
list2 = list(list1)
list1[0] = 5
print(list1)
o/p: [5,20,30,40] #change made in list1
print(list2)
o/p: [10,20,30,40] # change in list1 does not cause
any change in list2
Pgm No. 6
# Read two lists of integers. Display whether both lists are of same length,
whether the elements in each list sum up to the same value and whether
there are any values that occur in both the lists.
l1 = []
l2 = []
size = int(input('Enter the total no. of elements')) 
print('\nReading list1.........')
for i in range(size):
n = int(input('Enter the next number'))
l1.append(n)
print('\nReading list2.........')
for i in range(size):
n = int(input('Enter the next number'))
l2.append(n)
if len(l1) == len(l2):
print('Both lists are of same size', len(l1), len(l2))
else:
print('Both lists are of different size', len(l1), len(l2))
 
 
if sum(l1) == sum(l2):
print('Both lists sum upto same value', sum(l1), sum(l2))
else:
print('Both lists sum upto different values', sum(l1), sum(l2))
 
for i in l1:
for j in l2:
if i == j:
print(i, 'This value occurs in both lists')
Pgm 7
# Read a list of names. Find how many times the letter 'a' appears in the
list
names = []
count = 0
size = int(input('Enter total number of names'))
for i in range(size):
n = input('Enter a name')
names.append(n)
 
for i in names:
for j in i:
if j == 'a':
count = count + 1
print('No. of times letter a occurs is ', count)
Pgm No 8.
# To search for an element ‘x’ in a given list of n integers
my_list = []
n = int(input('Enter the size'))
 
for i in range(n):
num = int(input('Enter the number'))
my_list.append(num)
 
key = int(input('Enter the search element'))
flag = 1
for i in my_list:
if i == key:
flag = 0
break
if flag == 0:
print(‘Element found’)
else:
print('Element not found')
Pgm 9
# Read a set of names till the user inputs ‘AAA’. Sort these names into
alphabetical order.
 
names = []
input_names = []
 
while(1):
name = input('Enter a student name')
if name != 'AAA':
names.append(name)
else:
break
input_names = list(names) #copying lists
print(input_names)
names.sort()
print(input_names)
print('\n The sorted names are‘,names)
List Comprehension
• Range function generates sequence of integers with
fixed increments
• List comprehension is used to generate varied
sequences
• Ex1:
• >>[x ** 2 for x in [1,2,3]]
• >>[1, 4, 9]
Comprehensions in Python
• Comprehensions in Python provide us with a short and concise way
to construct new sequences (such as lists, set, dictionary etc.) using
existing sequences which have been already defined.
Types of comprehensions:
• List Comprehensions
• Dictionary Comprehensions
• Set Comprehensions
• Generator Comprehensions
• Basic structure of List Comprehension:
output_list = [output_exp for var in input_list if (var satisfies this condition)]

- if condition is optional.
- List comprehensions can contain multiple for (nested list comprehensions).
Example:
Create a list of square of all odd numbers from 1 to 10.
# Constructing output list using for loop
output_list = []
for x in range(1, 10):
if x%2==1:
output_list.append(x** 2)
print("Output List using for loop:", output_list)
# Constructing output list
# using list comprehension

output_list= [x**2 for x in range(1, 10) if x%2==1]

print("Output List using list comprehension:",output_list)


List Comprehension…..
• Ex 2:
[x ** 2 for x in range (5)]
o/p: [0,1,4,9,16]
• Ex 3:
nums = [-1, 1, -2, 2, -3, 3, -4, 4]
[x for x in nums if x>=0]
o/p: [1,2,3,4]
List Comprehension…..
• Ex4:
[ord(ch) for ch in ‘Hello’]
o/p: [72,101,108,108, 111]
• Ex5:
vowels = [‘a’,’e’,’I’,’o’,’u’]
w = ‘Hello’
[ch for ch in w if ch in vowels]
o/p: [‘e’,’o’]
Pgm 1 - List Comprehension
• Read a list of integers from the user till the user
inputs 000. Using list comprehension create new
lists namely
1) Square, where each element is a square of the
corresponding element in the input list
2) Positive, with only positive numbers in the input
list

74
Pgm 1
inp = []
square = []
positive = []
 
while(1):
n = int(input('Enter a number'))
if n != 000:
inp.append(n)
else:
break
Pgm 1…..
# using loop
for i in range(0,len(inp)):
square.append(inp[i] * inp[i])
if inp[i] > 0:
positive.append(inp[i])
Pgm 1 using list comprehension…
int = []
#square = []
#positive = []
 
while(1):
n = int(input('Enter a number'))
if n != 000:
inp.append(n)
else:
break
square = [i* i for i in inp]
print(square)
 
positive = [i for i in inp if i>0]
print(positive)
Pgm 2 List Comprehension
• Using list comprehension create two lists
1) Odd - list of odd integers from 1 to 10.
2) Even – list of even integers from 1 to 10.

78
Pgm 2
odd = [i for i in range(1,11) if i%2 !=0]
even = [i for i in range(1,11) if i%2 == 0]
 
print(odd)
print(even)
Nested Lists
• Lists can contain elements of any type…another list
• Ex:
• class_grades = [ [85,91,89], [78, 81, 86], …..]
• is a list of exam scores for each student in a given
class.
• class_grades[0] = [85,91,89]
• class_grades[1] = [78,81,86].
Nested Lists
• The first exam grade of the first student
class_grades[0][0]
o/p: 85.
Pgm 3 Calculate the class average of the first course.

class_grades = [ [85,91,89], [78, 81, 86] ]

sum = 0
#course_index = 0
for k in range(0, len(class_grades)):
sum = sum + class_grades[k][course_index]

average = sum/float(len(class_grades))
print(‘\n Average in course’, course_index+1, ’is ’, average)
Pgm 4 Average of each course
class_grades = [ [85,91,89], [78, 81, 86] ]
#average in each course

for course_index in range(0, 3):


sum = 0
for student in range(0,len(class_grades)):
sum = sum + class_grades[student][course_index]
print('\nAverage in course',course_index + 1,
'is',float(sum)/len(class_grades))
Pgm 5
• Read two matrices of order nrows x ncols and find
their sum.

84
a = []
b = []
c = []
nrows = int(input('Enter the no. of rows'))
ncols = int(input('Enter the no. of columns'))
print('Enter Matrix A')
for i in range(0,nrows):
row = [] #initialize a row as a list
print('Enter the elements of row',i)
for j in range(0,ncols):
n = int(input('Enter a number'))
row.append(n) # append this row element to the row list
a.append(row) # append this row to the nested list
print('\n Matrix A is')
for i in a:
print(i)
print('Enter Matrix B')
for i in range(0,nrows):
row = [] #initialize a row as a list
print('Enter the elements of row',i)
for j in range(0,ncols):
n = int(input('Enter a number'))
row.append(n) # append this row element to
# the row list
b.append(row) # append this row to the nested list
print('\n Matrix B is')
for i in b:
print(i)
 
# Matrix addition using nested loops
for i in range(0,nrows):
row = [] #intialize a row as a list
for j in range(0, ncols):
val = a[i][j] + b[i][j]
row.append(val) # append this row element to
the row list
c.append(row) # append this row to the nested list
Pgm 5
print('The Resultant Matrix')
for i in c:
print(i)
#matrix addition using list comprehension
a=eval(input('enter the first matrix'))
b=eval(input('enter the second matrix'))
sum=[[a[i][j]+ b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
print(sum)
for k in sum:
print(k)
Tuples
• A tuple is an immutable linear data structure.
• In contrast to lists, once a tuple is defined, it
cannot be altered.
• Otherwise tuples are same as lists essentially.
• Tuples are denoted by parenthesis, but tuple
elements are accessed using square brackets.
• Ex:
• num = (10,20,30)
• student = (‘John’, 48, ‘Computer Science’, 3.42)
Creating Tuples…..
• Empty tuple
• >>> tup1 = ()
• Tuples of one element should have a comma following
the element
• Ex: num = (10,)
• >>> my_tuple = ("hello") # only parentheses is not
enough for creating a tuple with one element
• >>> type(my_tuple)
• <class 'str'>
• >>> my_tuple = ("hello",)
• >>> type(my_tuple)
• <class 'tuple'>
Creating Tuples…..
• >>> my_tuple = "hello", # parentheses is
optional
• >>> type(my_tuple)
• <class 'tuple'>
Tuples…..
• Creating a tuple from a list
• list = [1,2,3]
tpl = tuple(list) #converts a list to a tuple
print(tpl)
?????
• Creating a tuple from range()
• tpl = tuple(range(4,9,2))
print(tpl)
??????
Accessing Elements of a Tuple
• my_tuple = ('p','e','r','m','i','t‘)
my_tuple[0]
'p'
my_tuple[6] # index must be in range
IndexError: list index out of range
my_tuple[2.0] # index must be an integer

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))


n_tuple[0][3] # nested index
's‘
n_tuple[-1] #last element
(1,2,3)
Slicing
• We can access a range of items in a tuple by using the slicing operator
(colon).
• >>> my_tuple = ('p','r','o','g','r','a','m','i','z')
• >>> my_tuple[1:4] # elements 2nd to 4th
• ('r', 'o', 'g')
• >>> my_tuple[7:] # elements 8th to end
• ('i', 'z')
• >>> my_tuple[:] # elements beginning to end
• ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
• >>>my_tuple[::2]
• ????
Changing/Deleting a Tuple
• Unlike lists, tuples are immutable.
• This means that elements of a tuple cannot be
changed once it has been assigned.
• But if the element is itself a mutable datatype like
list, its nested items can be changed.
• We can also assign a tuple to different values
(reassignment).
Changing/Deleting a Tuple…..
• >>> my_tuple = (4, 2, 3, [6, 5])
• >>> my_tuple[1] = 9 # we cannot change an element
• ...
• TypeError: 'tuple' object does not support item assignment
• >>> my_tuple[3] = 9 # we cannot change an element
• ...
• TypeError: 'tuple' object does not support item assignment
• >>> my_tuple[3][0] = 9 # but item of mutable element can be changed
• >>> my_tuple
• (4, 2, 3, [9, 5])
• >>> my_tuple = ('p','r','o','g','r','a','m','i','z') # tuples can be reassigned
• >>> my_tuple
• ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Changing/Deleting a Tuple…..
• We cannot delete or remove items from a tuple. But deleting the
tuple entirely is possible using the keyword del.
• >>> my_tuple = ('p','r','o','g','r','a','m','i','z')
• >>> del my_tuple[3] # can't delete items
• ...
• TypeError: 'tuple' object doesn't support item deletion
• >>> del my_tuple # can delete entire tuple
• >>> my_tuple
• ...
• NameError: name 'my_tuple' is not defined
Tuple Membership Test
• We can test if an item exists in a tuple or not, using the
keyword in.
• >>> my_tuple = ('a','p','p','l','e',)
• >>> 'a' in my_tuple
• True
• >>> 'b' in my_tuple
• False
• >>> 'g' not in my_tuple
• True
Functions/Methods to Process Tuples
• tpl =(10,20,10,30)
>>>len(tpl) ????
>>>min(tpl) ????
>>>max(tpl) ????
>>>tpl.count(10) ????
>>>tpl.index(20) ???
>>>sorted(tpl) ????
>>>sorted(tpl,reverse=True) ???
Read a tuple using eval()
• num = eval(input(“enter the elements in ():”))
• eval() checks whether the input is a list or a tuple
based on the format of the brackets in the input
• If input is [1,2,3,4,5] then num is a list
• If input is (1,2,3,4,5) then num is a tuple
Pgm 1:
• Read the marks of ‘n’ students in a course as a tuple and find the sum, average, highest and
lowest.

marks = eval(input("Enter elements in () :"))


sum = 0
n = len(marks)
for i in range(n):
sum = sum + marks[i]
print("Sum of all marks = ", sum)
print("Average of the course = ", sum/n)
print("Highest mark = ", max(marks))
print("Lowest mark = ", min(marks))
Advantages of Tuples over Lists
• Tuples and list look quite similar except the fact that one is
immutable and the other is mutable.
• We generally use tuple for heterogeneous (different) data types and
list for homogeneous (similar) data types.
• There are some advantages of implementing a tuple than a list. Here
are a few of them.
1. Since tuple are immutable, iterating through tuple is
faster than with list. So there is a slight performance
boost.
2. Tuples that contain immutable elements can be used
as key for a dictionary. With list, this is not possible.
Unpacking a tuple
tuplex = ‘Harry Potter’, 48, 88, 93
print(tuplex)
name, n1, n2, n3 = tuplex
#unpack a tuple in variables
print(name, ”has scored a total of”, n1 + n2 + n3)
#The number of variables must be equal to the
number of items of the tuple
n1, n2, n3, n4= tuplex

104
Adding an item to a tuple
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new
elements.
#using merge of tuples with the + operator you can
add an element and it will create a new tuple
tuplex= tuplex + (9,)
print(tuplex)

105
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
print(listx)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)

106
Converting a tuple to a string
tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's')
str = ''.join(tup)
print(str)

107
Removing an item from a tuple
tuplex = "w", “e”, "r", “i", “d", “e", "r", “s"
print(tuplex)
#tuples are immutable, so you can not remove
elements
#using merge of tuples with the + operator you can
remove an item and it will create a new tuple
#remove "r" from the tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)

108
Removing…
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("c")
#converting the list to tuple
tuplex = tuple(listx)
print(tuplex)

109
• Write a Python script that prompts the user to enter
types of fruits and their corresponding weight in pounds.
The program should then print the information in the
form of fruit, weight first
a) sorted using alphabetical order of fruit names and then
b) in ascending order of fruit weights and
c)in descending order of fruit weights
Using a list of tuples
• Input : [(‘grapes’,56), (‘orange’,78), (‘apple’, 89)]

• Output 1 : alphabetical order of fruit names


[(‘apple’, 89) , (‘grapes’,56), (‘orange’,78)]
• Output 2 : ascending order of fruit weights
[(‘grapes’,56), (‘orange’,78), (‘apple’, 89) ]
• Output 3: descending order of fruit weights
[(‘apple’, 89), (‘orange’,78), (‘grapes’,56)]

111
fruits = ()

for i in range(1,3):
f = ()
name = input('Enter a name')
f.append(name)
weight = input('Enter a weight')
f.append(weight)
fruits.append(f)

AttributeError: 'tuple' object has no attribute 'append'


#sorting a list of tuples
import operator
fruits = []
sort_first = []
sort_second = []
sort_third= []
 num = int(input('Enter the no. of fruits'))
 
for i in range(num):
f = eval(input("Enter a fruit name and its weight in ()"))
fruits.append(f)

print(fruits)

sort_first = sorted(fruits)
sort_second = sorted(fruits, key = operator.itemgetter(1))
sort_third = sorted(fruits, key = operator.itemgetter(1), reverse = 1)
print(sort_first)
print(sort_second)
print(sort_third)
EXERCISES ON TUPLES
1. Create an empty tuple.
t = ()
print(t)
2. Initialize a tuple at compile time.
t = ("Anaconda", 34, 56.99)
print(t)
3. Create a tuple at run time.
ANSWER 1:
#create a list and convert the list to a tuple
age = []
 
while (1):
a = int(input("Enter the age of a person"))
if a<0:
break
else:
age.append(a)
 
t = tuple(age)
print(t)
 
Ans2:
#create an empty tuple and use merge operator
t = ()
while (1):
a = int(input("Enter the age of a person"))
if a<0:
break
else:
t = t + (a,)
 
print(t)
4. Inserting a set of items into a tuple at a specific index
Ans:
#inserting a tuple into a tuple at a specific index
t = (2,3,4,5,6)
t = t[:2] + (3.1,3.2,3.3,3.4) + t[2:]
print(t)
5. Create a tuple of names and find the number of occurrences of
each name in the tuple.
t = ()
while (1):
a = input("Enter the name of a person")
if a=="AAA":
break
else:
t = t + (a,)
print(t)
unique = []
for i in t:
if i not in unique:
unique.append(i)
print("The name {0} occurs {1} times in the input".format(i,t.count(i)))
6. Modify the above program to find the most frequent name in the list.
Expected O/p: Enter the name of a person:Hary
Enter the name of a person:Potter
Enter the name of a person:Hary
Enter the name of a person:Bob
Enter the name of a person:Alan
Enter the name of a person:AAA
The most frequent name is :Hary
Program:
from statistics import mode
t = ()
while (1):
a = input("Enter the name of a person")
if a == "AAA":
break
else:
t = t + (a,)
print("The most frequent name is", mode(t))
mean() Arithmetic mean (“average”) of data.
fmean() Fast, floating point arithmetic mean.
geometric_mean() Geometric mean of data.
harmonic_mean() Harmonic mean of data.
median() Median (middle value) of data.
median_low() Low median of data.
median_high() High median of data.
median_grouped() Median, or 50th percentile, of grouped data.
mode() Single mode (most common value) of discrete
or nominal data.
multimode() List of modes (most common values) of
discrete or nomimal data.
Divide data into intervals with equal
quantiles() probability.
7. Create a list of names as a tuple. Remove a given name from this list.
Sample Input and Output:
Enter the name of a person : Hary
 
Enter the name of a person : Potter
 
Enter the name of a person : Ariana
 
Enter the name of a person : Stuart
 
Enter the name of a person : AAA
 
Enter the name to be removed : Ariana
The list after removing Ariana is : ('Hary', 'Potter', 'Stuart')
t = ()
while (1):
a = input("Enter the name of a person")
if a == "AAA":
break
else:
t = t + (a,)
remove = input("Enter the name to be removed")
 
for i in range(len(t)):
if t[i] == remove:
t = t[:i] + t[i+1:]
break
print("The list after removing {0} is{1}".format(remove, t))
8. Create a shopping list having the item name and its quantity as a list of tuples.
Ex: The Shopping List [('egg', 3), ('bread', 4), ('butter', 1)]
shopping_list = []
while (1):
a = eval(input("Enter the name and quantity of an item as a ()"))
if a==():
break
else:
shopping_list.append(a)
 
print("The Shopping List",shopping_list)
Dictionaries
• Indexed data structure - the elements are ordered.
Ex – lists – first element – index 0 and so on
• Associative data structure – elements are unordered and
specified by an associated key-value pair.
• Dictionary – mutable associative data structure of variable length.
Ex: dictionary with average temperatures in a week.
• daily_temp = {‘sun’:68.8, ‘mon’: 72.3, ‘tue’:54.6, ‘wed’:54.2,
‘thur’:76.3, ‘fri’:66.6, ‘sat’:52.1}
Keys are (‘sun’, ‘mon’,…..etc)

127
• Written in curly brackets, where each element are in the
form of key-value pair.
Ex: dictionary with average temperatures in a week.
daily_temp = {‘sun’:68.8, ‘mon’: 72.3, ‘tue’:54.6,
‘wed’:54.2, ‘thur’:76.3, ‘fri’:66.6, ‘sat’:52.1}
Keys are (‘sun’, ‘mon’,…..etc)
Values are 68.8, 72.3, 54.6,……etc.
• Unordered, have named indexes (keys act as indexes).
• Mutable
Dictionaries
• Each element of a dictionary is accessed using its key
Ex: daily_temp[‘mon’]
• No logical first element, second element and so on…
• Keys are generally immutable data types - tuple
Ex: temps = { (‘Jan’, 2, 2004):34.8, (‘Feb’, 6, 2015): 54.7,
(‘Mar’, 12,2007):64.9}
• Red represents key and blue represents value
Accessing Value
• dict1={"apple":50,"orange":20,"banana":30}
• print(dict1["apple"])
• o/p: 50
• print(dict1["orange"])
• o/p:20
• print(dict1["banana"])
• o/p:30

130
Ex: Comparing the temp. of Saturday & Sunday

daily_temp = {‘sun’:68.8, ‘mon’: 72.3, ‘tue’:54.6, ‘wed’:54.2,


‘thur’:76.3, ‘fri’:66.6, ‘sat’:52.1}

if daily_temp[‘sun’] > daily_temp[‘sat’]:


print(‘Sunday was the warmer weekend’)
elif daily_temp[‘sun’] < daily_temp[‘sat’]:
print(‘Saturday was the warmer weekend’)
else:
print(‘Saturday and Sunday were equally warm’)
Example 1
• Given the daily average temperatures of a particular week,
find the average temperature for a particular day of the week
using a list.
#daily temperature using a list
temps = [68.8, 70.2, 67.2, 71.8, 73.2, 75.6, 74.0]
 
day = input('Enter a day - sun, mon, tue, wed, thur, fri or sat')
if day == 'sun':
dayname = 'SUNDAY'
t = temps[0]
elif day == 'mon':
dayname = 'MONDAY'
t = temps[1]
elif day == 'tue':
dayname = 'TUESDAY'
t = temps[2]
elif day == 'wed':
dayname = 'WEDNESDAY'
t = temps[3]
elif day == 'thur':
dayname = 'THURSDAY'
t = temps[4]

133
elif day == 'fri':
dayname = 'FRIDAY'
t = temps[5]
elif day=='sat':
dayname = 'SATURDAY'
t = temps[6]
else:
print('Invalid input')
print('The temperature on {0} is {1}'.format(dayname,t))

134
Example2
• Given the daily average temperatures of a
particular week, find the average temperature for
a particular day of the week using a dictionary.

135
#daily temperature using a dictionary
temps = {'sun':68.8, 'mon':70.2,'tue': 67.2,'wed':71.8,'thur': 73.2,'fri': 75.6, 'sat':74.0}

daynames = {'sun':'SUNDAY', 'mon':'MONDAY','tue': 'TUESDAY','wed':'WEDNESDAY',


'thur': 'THURSDAY','fri': 'FRIDAY', 'sat':'SATURDAY'}

day = input('Enter a day - sun, mon, tue, wed, thur, fri or sat')
print('The temp on {0} is {1}'.format(daynames[day],temps[day]))

136
Operations on a Dictionary
Operation Results
dict() Creates an empty dictionary
Ex: d = dict()
d1 = {}
dict(s) Creates a new dictionary with keys and their associated values from a
sequence, s
Ex: fruit_price = dict(fruit_data)
Where fruit_data is(possibly read from a file)
[[‘apples’,0.66], [‘oranges’, 0.88], ……]

len(d) Length of the dictionary/No. of key value pairs

d[key] = value Sets the associated value for key.

del d[key] Removes key and associated value from the dictionary d
daily_temps={('sun',1): 68.8, ('mon',2): 70.2, ('tue',3): 67.2, ('wed',4): 71.8}

1. Print the length of the dictionary


print("length of dict={0}".format(len(daily_temps)))
o/p: length of dict=4

2. Adding a key/value pair into the dictionary


daily_temps[('thur',5)]=80.2
o/p:
{('sun', 1): 68.8, ('mon', 2): 70.2, ('tue', 3): 67.2, ('wed', 4): 71.8, ('thur', 5):
80.2}

138
3. change value of key (‘mon’,2) in dictionary
daily_temps[('mon',2)]=88.2
print(daily_temps)
o/p:{('sun', 1): 68.8, ('mon', 2): 88.2, ('tue', 3): 67.2, ('wed', 4): 71.8,
('thur', 5): 80.2}

4. deleting value from dictionary using key


del daily_temps[('sun',1)]
print(daily_temps)

o/p:{('mon', 2): 88.2, ('tue', 3): 67.2, ('wed', 4): 71.8, ('thur', 5): 80.2}

139
Operations on a Dictionary
Operation Results

key in d True if key exists in dictionary d, otherwise False

dict.pop(key) Deletes the value with the corresponding key


dict.keys() Returns all keys of the dictionary
dict.values() Returns all values in the dictionary
dict1.update(dict2) Adds the items from dict2 to dict1
Ex: dict1={1:10, 2:20}
dict2 ={3:30,4:40}
dict1.update(dict2)
print(dict1)
daily_temps={('sun',1): 68.8,('mon',2): 70.2,('tue',3): 67.2,('wed',4): 71.8}

5. displays only keys


print(daily_temps.keys()) # displays only keys
0/p: [('sun', 1), ('mon', 2), ('tue', 3), ('wed', 4)]

6. display only values


print(daily_temps.values())
0/p : [68.8, 70.2, 67.2, 71.8]

7. deletes key value ('sun',1)


daily_temps.pop(('sun',1)) # print(daily_temps)
o/p : {('mon', 2): 70.2, ('tue', 3): 67.2, ('wed', 4): 71.8}

141
8. Membership Testing
if ('mon',2) in daily_temps:
print("true")
o/p true

if ('sun',1) in daily_temps:
print("true")
else:
print("false")
o/p false
9. Updating a dictionary
dict1={1:10, 2:20}
dict2 ={3:30,4:40}
dict1.update(dict2)
print(dict1)
o/p:{1: 10, 2: 20, 3: 30, 4: 40}

142
Operations on a Dictionary
Operation Results
all(dict) Returns true if all keys of a dictionary are true; false otherwise

any(dict) Returns true if any key of the dictionary is true; false if the
dictionary is empty
sorted(dict) Returns the sorted list of keys

dict.clear() Deletes all items of the dictionary

dict.get(key, Returns value of the key, default if key not in dictionary


default=None) dict1={“apple”:50,”papaya”:30}
dict1.get(“apple”,” ”) -------50
dict1.get(“orange”,” ”)--------’’ ’’
#any()
dict2 = {0: 'False', 0: 'False'}
#items() print(any(dict2))
car = {
#clear()
"brand": "Ford", car = {
"model": "Mustang", "brand": "Ford",
"model": "Mustang",
"year": 1964} "year": 1964
print(car.items()) }
print(car.clear())
print(car)
#all()
dict1 = {1: 'True', 3: 'True'} #get() method
print(all(dict1)) car = {
"brand": "Ford",
"model": "Figo",
"year": 2011
}
x = car.get("mode")
print(x)
#sort using keys
fruit_prices = {'apples':0.66,
'pears':0.25,'peaches':0.74,'bananas':0.49}
print(sorted(fruit_prices))
print()
print(sorted(fruit_prices.items()))
#sort using values
import operator
sorted_list=[]
orders = {'cappuccino': 54, 'latte': 56, 'espresso': 72, 'americano': 48, 'cortado': 41 }
#print(sorted(orders.items()))
sorted_list = sorted(orders.items(), key = operator.itemgetter(1))
print(sorted_list)
print(dict(sorted_list))
Dictionary Comprehension

• Dictionary comprehension is an elegant and concise way to


create new dictionary from an iterable in Python.
• Dictionary comprehension consists of an expression pair
(key: value) followed by for statement inside curly braces {}.
• A dictionary comprehension can optionally contain more for
or if statements.

147
• #make a dictionary with each item being a pair of a
number and its square.
>>>squares = {x: x*x for x in range(6)}
>>>print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

>>>odd_squares = {x: x*x for x in range(11) if x%2 == 1}


>>>print(odd_squares)
# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

148
EXERCISE PROGRAMS
1. Given an integer number ‘n’, write a program to generate a dictionary with (i, i*i)
such that I is an integer between 1 and n(both included). The program should then
print the dictionary.
Input/Output
Enter a number5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

n = int(input('Enter a number'))
d = dict()
for i in range(1,n+1):
d[i] = i * i
print(d)
2. Write a Python program to read a list of list having the name of the day and
the corresponding temperature of days in a week
Ex: temps = [[‘sun’, 68.2], [‘mon’,56.6],….]
Convert this to a dictionary. Read a particular day name and its temperature.
Add this to the dictionary only if it doesn’t exists.
Sample Input and Output:
Enter a day and temperature as a list['Sun',34.5]
 
Enter a day and temperature as a list['Wed',25.8]
The input list is [['Sun', 34.5], ['Wed', 25.8]]
{'Sun': 34.5, 'Wed': 25.8}
 
Enter a day to add: Tue
 
Enter a temp: 32
Updated temperatures
{'Sun': 34.5, 'Wed': 25.8, 'Tue': 32.0}
temp_dict = {} #dictionary initialized
temp_list =[] #list of list initialized
for i in range(2):
day_temp = eval(input("Enter a day and temperature as a list"))
temp_list.append(day_temp) 
print("The input list is",temp_list)

temp_dict = dict(temp_list) #convert list of lists to a dictionary


print(temp_dict)
 
day = input('Enter a day to add')
if day in temp_dict:
print('Day already exists')
else:
temp_dict[day] = float(input('Enter a temp'))
print('Updated temperatures')
print(temp_dict)
3. Write a Python program which initializes a dictionary having each day and
its temperature.
The program should return a list of days on which temperature was between 70
and 79 degrees.
Sample Input and Output:
temps = {'sun':68.8, 'mon':70.2, 'tue':67.2, 'wed':71.8, 'thur':73.2, 'fri':75.6,
'sat':74.0}
Days in which average temperature is between 70 and 79
['mon', 'wed', 'thur', 'fri', 'sat']
temps = {'sun':68.8, 'mon':70.2, 'tue':67.2, 'wed':71.8, 'thur':73.2, 'fri':75.6, 'sat':74.0}
days = []
for d in temps:
if temps[d] >=70 and temps[d]<=79:
days.append(d)
 
print('Days in which average temperature is between 70 and 79')
print(days)
4. Initialize a dictionary myDict={‘even’ : 0, ’odd’ : 0}. Read integer values from user till the user
input is -1. For every even or odd input increase the corresponding count in the dictionary.
INPUT-1 10
OUTPUT-1: myDict={‘even’ : 1, ’odd’ : 0}
INPUT-2 : 11
OUTPUT-2: myDict={‘even’ : 1, ’odd’ : 1}

d= {'even':0,'odd':0}
while(1):
x = int(input("Enter the number"))
if x == -1:
break
  if(x%2 == 0):
d['even'] = d['even']+1
else:
d['odd'] = d['odd'] + 1
print(d)
5. Initialize a dictionary {0 : [ ], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}.
Read any number of integer values from the user till the user inputs -1. Every input integer number
‘n’ has be to be placed in the list whose key is given by n % 9.
INPUT : 9
OUTPUT: {0 : [9], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}
INPUT : 7
OUTPUT : {0 : [9], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [7 ], 8: [ ]}
INPUT : 18
OUTPUT : {0 : [9,18], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}
d = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}
while(1):
x = int(input("Enter the value of n"))
if x == -1:
break
else:
key = x%9
d[key].append(x)
print(d)
6. Create a dictionary having name and mark of students in a class of 3.
Ex: {"JAMES":80,"ROHITH":87,"ISHITHA":67}
 
The program should then
A )find the number of students in the class B)Find the class average
C)Find the number of students above class average D) Find the topper
E) A student has applied for recheck. Replace the mark of a student given his/her name with the new
mark.
F) Print the updated dictionary
Sample Input and Output:
Enter the IDNO and MARK of each student as a {}{"JAMES":80,"ROHITH":87,"ISHITHA":67}
The student dictionary is {'JAMES': 80, 'ROHITH': 87, 'ISHITHA': 67}
The number of students are 3
The class average is = 78.0
The number of students above class average is 2
The Topper of the class is ROHITH
 
Who has applied for recheck?ISHITHA
 
What is the new mark?72
The dictionary after rechecks is {'JAMES': 80, 'ROHITH': 87, 'ISHITHA': 72}
import operator
students = eval(input("Enter the IDNO and MARK of each student as a {}"))
print("The student dictionary is", students)
print("The number of students are",len(students))

#to find class average


sum=0
for k in students:
sum = sum + students[k]
class_average = sum/len(students)
print("The class average is =",class_average)
#to find no. of students above class average
count=0
for k in students:
if students[k] > class_average:
count = count + 1
print("The number of students above class average is", count)

#to find the topper of the class


out = sorted(students.items(), key = operator.itemgetter(1), reverse = 1)
topper = out[0][0]
print("The Topper of the class is",topper)
#to implement recheck
recheck_name = input("Who has applied for recheck?")
new_mark = int(input("What is the new mark?"))
 
students[recheck_name] = new_mark
print("The dictionary after rechecks is",students)

# an alternative to find the name with the highest value in the dictionary
#max(students.items(), key = operator.itemgetter(1))[0]
7. Create a dictionary using comprehension from two sequences.
 
Syntax: {key:value for (key,value) in iterable}

keys = ['a', 'b', 'c']


values = [1, 2, 3]
{i:j for (i,j) in zip(keys, values)}
 
Output : {'a': 1, 'b': 2, 'c': 3}
8. From a list of names, using comprehension create a dictionary which has the
first character of each name as the key and the corresponding name as its value.
Sample Input and Output
Enter a list of names as a []["DELHI","MUMBAI","BANGALORE","CHENNAI"]
{'D': 'DELHI', 'M': 'MUMBAI', 'B': 'BANGALORE', 'C': 'CHENNAI'}

names = eval(input("Enter a list of names as a []"))


d = {i[0]:i for i in names}
print(d)
9. Given input = ["ReD", "GrEeN", "BluE"],
create a dictionary out = {'red': 'RED', 'green': 'GREEN', 'blue': 'BLUE'}.

l = ["ReD", "GrEeN", "BluE"]


out = {c.lower():c.upper() for c in l}
print(out)
10. Write a program that inverts a dictionary. Makes the keys as values and
values as keys respectively.
Sample Input and Output:
Original Dictionary : {1: 'rose', 2: 'jasmine', 3: 'lilly', 4: 'tulip'}
Inverted Disctionary : {'rose': 1, 'jasmine': 2, 'lilly': 3, 'tulip': 4}
d = {1 : "rose", 2 : "jasmine", 3 : "lilly", 4: "tulip"}
d1 = {}
 
for (key, value) in d.items():
d1[value] = key
 
print("Original Dictionary :",d)
print("Inverted Disctionary :",d1)
 
Thank You

166

You might also like