Dictionary and Tuple in Python – Difference in Properties

In this post, we will learn about tuples and dictionaries in python and how to use tuples as dictionary keys.


What is tuple in python?

A tuple is an ordered and immutable collection. Tuples can hold homogeneous values as well as heterogeneous values(integers, floats, strings, lists, dictionaries, etc). Tuples are sequential, thus they can be indexed and sliced.

Tuple Creation, Packing, and Unpacking

Syntactically, a tuple is a comma-separated list of values.

#homogeneous tuple
tup=1,2,3,4,5,6,7,8,9 
print(type(tup)) 
#Output: <type 'tuple'>

#single value without comma
a='a'
print(type(a))
#Output: <type 'str'>

#single value with comma
a='a',
print(type(a))
#Output: <type 'tuple'>

#hetrogeneous values
tup2=1,'str',['list',1,2,3],('t','u','p','l','e')
print(type(tup2)) 
#Output: <type 'tuple'>


In python, this type of tuple declaration is called packing of a tuple, because it packs all left-hand side values together in a tuple.

Parenthesis() are optional in tuples except for creating empty tuple. However, it is good practice to use parenthesis.

#empty tuple
tup1=()
print(type(tup1)) 
#Output: <type 'tuple'> 

#homogeneous values
tup= (1,2,3,4,5,6,7,8,9)
print(type(tup)) 
#Output: <type 'tuple'> 

#single value without comma 
a=('a') 
print(type(a)) 
#Output: <type 'str'> 

#single value with comma 
a=('a',)
print(type(a)) 
#Output: <type 'tuple'>
 
#hetrogeneous values 
tup2= (1,'str',['list',1,2,3],('t','u','p','l','e')) 
print(type(tup2)) 
#Output: <type 'tuple'>

Creating a tuple containing one element is a bit tricky. The single element should have a comma at the end because it is the comma that defines a tuple not parenthesis.

Tuple unpacking allows extracting tuple elements automatically by assigning each value on the right-hand side to its respective variable on the left side. Thus the number of variables on left must match the number of values on right. All the expressions on the right side are evaluated before any of the assignments.

tup1 = (1,2,3)
a,b,c = tup1
print(b)
#Output: 2

a,b,c,d,e = 1,2,3,4,5
print(c)
#Output: 3

tup2 = (5,6)
x,y,z = tup2
#Output: ValueError: need more than 2 values to unpack

y,z= 'x','y','z'
#Output: ValueError: too many values to unpack (expected 2)

Dictionary in python

Dictionary is an unordered collection of mutable values indexed by unique keys. Dictionaries are just like map(), storing, and retrieving
elements by referencing a key. Thus keys must be of an immutable data type(Strings, Tuples, Integers, etc.) whereas values can be of any type python supports, there are no restrictions on dictionary values. As dictionaries are referenced by key, they have very fast lookups. The syntax of a dictionary is as follows:

Dictionary_name = {key: value}

dict = {
  "fruit": "Mango",
  "quantity": 5,
  "colour": "yellow"
}

Dictionaries can be created in many ways:

# dictionary with integer keys
dict1 = {1: 'Python', 2: 'Java'}

# empty dictionary
dict2 = {}

# dictionary with mixed keys
dict3 = {'name': 'Joy', 'marks': [62, 54, 83], 1: 'Maths', 2:'Physics', 3:'Chemistry'}

# using built-in class dict()
dict4 = dict({1:'Python', 2:'Java'})

# from sequence having each item as a pair
dict5 = dict([(1,'Python'), (2,'Java')])

# using dictionary comprehension
dict6 = {x: i**2 for x in range(20)}

 

Dictionary and tuple:

A dictionary key must be of hashable type because a hashable object does not change during its lifetime. Therefore, tuples can be used as dictionary keys as they are unchangeable. However, neither a list nor another dictionary can be used as a dictionary key, because lists and dictionaries are mutable.

#dictionary keys as tuple 
t=(1,2) 
d={} 
d[t]=42 
print(d) #Output: {(1, 2): 42}

#dictionary keys as list 
l=[1,2] 
d={} 
d[l]=42 
#Output: TypeError: unhashable type: 'list' 

Tuples can be used to make a composite key to dictionaries.

Example: Creating  to store marks of students by mapping roll numbers and subjects to marks:

marks={(1,'Maths'):96,
       (2,'Maths'):38,
       (3,'Maths'):58,
       (1,'Physics'):83,
       (2,'Physics'):23,
       (3,'Physics'):46,
       (1,'Chemistry'):98,
       (2,'Chemistry'):43,
       (3,'Chemistry'):57}

For loop can be used to iterate through this Dictionary.

for roll_no,subject in marks:
    print(roll_no,subject,marks[(roll_no,subject)])
#Output: 1 Maths 96
         2 Maths 38
         3 Maths 58
         1 Physics 83
         2 Physics 23
         3 Physics 46
         1 Chemistry 98
         2 Chemistry 43
         3 Chemistry 57

Tags: creating dictionary, dictionary, Dictionary in python, packing a tuple, packing and unpacking a tuple, Python, single element in tuple, Tuple, tuple and dictionary, tuple in python, tuple is hashable, unpacking a tuple

 

 

 

%d bloggers like this: