0% found this document useful (0 votes)
2 views16 pages

Tuple & Dict

The document provides an overview of tuples and dictionaries in Python, highlighting their characteristics, operations, and functions. Tuples are immutable ordered sequences, while dictionaries are unordered collections of key-value pairs. It also includes examples of operations and functions applicable to both data structures, such as indexing, membership, and creating inverted dictionaries.

Uploaded by

Bhargavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Tuple & Dict

The document provides an overview of tuples and dictionaries in Python, highlighting their characteristics, operations, and functions. Tuples are immutable ordered sequences, while dictionaries are unordered collections of key-value pairs. It also includes examples of operations and functions applicable to both data structures, such as indexing, membership, and creating inverted dictionaries.

Uploaded by

Bhargavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Tuples

A tuple is a non-scalar type defined in Python. Just like a list, a


tuple is an ordered sequence of objects.
However, unlike lists, tuples are immutable, i.e. elements of a
tuple cannot be overwritten.
A tuple may be specified by enclosing in the parentheses, the
elements of the tuple (possibly of heterogeneous types),
separated by commas, for example, the tuple t1 comprises five
objects:
iii t1 = (4, 6, [2, 8], ’abc’, {3,4})
iii type(t1)
hclass0 tuple0 i

35 / 52
Tuples

If a tuple comprises a single element, the element should be


followed by a comma to distinguish a tuple from a parenthesized
expression, for example:
iii (2,)
(2,)
A tuple having a single element is also known as singleton tuple.
Another notation for tuples is just to list the elements of a tuple,
separated by commas:
iii 2, 4, 6
(2, 4, 6)
Elements of a tuple may be mutable
iii t1 = (1, 2, [3, 4])
iii t1[2][1] = 5
iii t1
(1, 2, [3, 5])
36 / 52
Tuple Operations

we summarize the operations on tuples and use the following


tuples t1 and t2 for the purpose of illustration:
iii t1 = (’Monday’, ’Tuesday’)
iii t2 = (10, 20, 30)

Operation Example
Multiplicationiii t1 ∗ 2
Operator ∗ (’Monday’, ’Tuesday’, ’Monday’, ’Tuesday’)
iii t3=t1 + (’Wednesday’,)
Concatenation
iii t3
Operator +
(’Monday’, ’Tuesday’, ’Wednesday’)
Length iii len(t1)
Operator len 2
iii t2[-2]
Indexing
20

37 / 52
Tuple Operations

Operation Example
Slicing Syntax: iii t1[1:2]
start:end:inc (’Tuesday’, )
iii min(t2)
Function min
10
iii max(t2)
Function max
30
Function sum iii sum(t2)
(not defined on strings) 60
iii ’Friday’ in t1
Membership operator in
False
Table 4: Summary of operations that can be applied on tuples

38 / 52
Functions Tuple and Zip

The function tuple can be used to convert a sequence to a tuple,


for example:
iii vowels = ’aeiou’
iii tuple(vowels)
(’a’, ’e’, ’i’, ’o’, ’u’)
The function zip is used to produces a zip object (iterable object),
whose ith element is a tuple containing ith element from each
iterable object passed as argument to the zip function.
We have applied list function to convert the zip object to a list of
tuples. For example,
iii colors = (’red’, ’yellow’, ’orange’)
iii fruits = [’cherry’, ’banana’, ’orange’]
iii fruitColor = list(zip(colors, fruits))
iii fruitColor
[(’red’, ’cherry’),(’yellow’, ’banana’),(’orange’, ’orange’)]

39 / 52
Functions count and index

The function count is used to find the number of occurrences of a


value in a tuple, for example:
iii age = (20, 18, 17, 19, 18, 18)
iii age.count(18)
The function index is used to find the index of the first occurrence
of a particular element in a tuple, for example:
iii age.index(18)
1

Function Explanation
T.count(e) Returns count of occurrences of e in Tuple T
T.index(e) Returns index of first occurrences of e in Tuple T
Table 5: Tuple Functions

40 / 52
Dictionary

Unlike lists, tuples, and strings, a dictionary is an unordered


sequence of key-value pairs.
Indices in a dictionary can be of any immutable type and are
called keys.
Beginning with an empty dictionary, we create a dictionary of
month number-month name pairs as follows:
iii month = {}
iii month[1] = ’Jan’
iii month[2] = ’Feb’
iii month[3] = ’Mar’
iii month[4] = ’Apr’
iii month
{1: ’Jan’, 2: ’Feb’, 3: ’Mar’, 4: ’Apr’}
iii type(month)
hclass0 dict 0 i

41 / 52
Dictionary
iii price = {’tomato’:40, ’cucumber’:30, ’potato’:20,
’cauliflower’:70, ’cabbage’:50, ’lettuce’:40, ’raddish’:30, ’carrot’:20,
’peas’:80}
iii price[’potato’]
20
iii price[’carrot’]
20
iii price.keys()
dict keys([’tomato’, ’cucumber’, ’potato’, ’cauliflower’, ’cabbage’,
’lettuce’, ’raddish’, ’carrot’, ’peas’])
iii price.values()
dict values([40, 30, 20, 70, 50, 40, 30, 20, 80])
iii price.items()
dict items([(’tomato’, 40), (’cucumber’, 30), (’potato’, 20),
(’cauliflower’, 70), (’cabbage’, 50), (’lettuce’, 40), (’raddish’, 30),
(’carrot’, 20), (’peas’,80)])
42 / 52
Dictionary

The search in a dictionary is based on the key. Therefore, in a


dictionary, the keys are required to be unique.
As keys in a dictionary are immutable, lists cannot be used as
keys.
Keys in a dictionary may be of heterogeneous types, for example:
iii counting = {1:’one’, ’one’:1, 2:’two’, ’two’:2}

43 / 52
Dictionary Operations
some operations that can be applied to a dictionary and illustrate
these operations using a dictionary of digit-name pairs:
digits = {0:’Zero’, 1:’One’, 2:’Two’, 3:’Three’, 4:’Four’, 5:’Five’,
6:’Six’, 7:’Seven’, 8:’Eight’, 9:’Nine’}

Operation Examples
Length operator len (number of iii len(digits)
key-value pairs in dictionary) 10
iii digits[1]
Indexing
’One’
iii min(digits)
Function min
0
iii max(digits)
Function max
9
Function sum (assuming keys iii sum(digits)
are compatible for addition) 45
44 / 52
Dictionary Operations

Operation Examples
iii 5 in digits
True
Membership operator in
iii ’Five’ in digits
False
Table 6: Summary of operations that can be applied on dictionaries

Consider a dictionary named as winter:


iii winter = {11:’November ’, 12: ’December’, 1:’January’,
2:’February’}
Membership operation in, and functions min, max and sum apply
only to the keys in a dictionary.

45 / 52
Dictionary Operations

Thus, applying these operations on the dictionary winter is


equivalent to applying them on winter.keys() as shown below:
iii 2 in winter, min(winter), max(winter), sum(winter)
(True, 1, 12, 26)
iii 2 in winter.keys(), min(winter.keys()), max(winter.keys()),
sum(winter.keys())
(True, 1, 12, 26)
We may remove a key-value pair from a dictionary using del
operator, for example:
iii del winter[11]
iii winter
{12: ’December’, 1: ’January’, 2: ’February’}
To delete a dictionary, we use del operator:
iii del winter

46 / 52
Dictionary Functions
Function Explanation
D.items() Returns an object comprising of tuples of
key-value pairs present in dictionary D
D.keys() Returns an object comprising of all keys of
dictionary D
D.values() Returns an object comprising of all values
of dictionary D
D.clear() Removes all key-value pairs from dictio-
nary D
D.get(key, default) For the specified key, the function returns
the associated value. Returns the default
value in the case key is not present in the
dictionary D
D.copy() Creates a shallow copy of dictionary D
D1.update(D2) Adds the key-value pairs of dictionary D2
to dictionary D1
Table 7: Dictionary Functions 47 / 52
Inverted Dictionary

Suppose we are maintaining a dictionary of words and their


meanings of the form word:meaning. For simplicity, we assume
that each word has a single meaning.
There might be a few words that may have shared meaning.
Given this dictionary, we wish to find synonyms of a word, i.e.
given a word, we wish to find the list of words that have the same
meaning.
For this purpose, we would like to build an inverted dictionary
invDict of meaning:list-of-words.
iiiEnter word meaning dictionary: {’dubious’:’doubtful’,
’hilarious’:’amusing’, ’suspicious’:’doubtful’, ’comical’:’amusing’,
’hello’:’hi’}
Inverted Dictionary:
{’doubtful’: [’dubious’, ’suspicious’], ’amusing’: [’hilarious’,
’comical’]}

48 / 52
Inverted Dictionary Code

1 def buildInvDict(dict1):
2 ’’’
3 Objective: To construct inverted dictionary
4 Input parameter: dict1: dictionary
5 Return value: invDict: dictionary
6 ’’’
7 invDict = {}
8 for key,values in dict1.items():
9 if value in invDict:
10 invDict[value].append(key)
11 else:
12 invDict[value] = [key]
13 invDict={x:invDict[x] for x in invDict if len(invDict[x]>1)
}
14 return invDict

49 / 52
Inverted Dictionary Code

1 def main():
2 ’’’
3 Objective: To find inverted dictionary
4 Input parameters: None
5 Return value: None
6 ’’’
7 wordMeaning = eval(input(’Enter word meaning dictionary:’))
8 meaningWord = buildInvDict(wordMeaning)
9 print(’Inverted dictionary:\n’, meaningWord)
10
11 # Statements to initiate the call to main function.
12
13 if __name__==’__main__’:
14 main()

50 / 52

You might also like