Sunday, 16 September 2018

Dictionaries, Tuples and Sets

Dictionaries 


Dictionaries are another important feature in Python. Python dictionaries are pretty much different from other languages' dictionaries. In most of the languages, dictionaries will usually hold only one type of value and will have limited functionality. However, in Python the story is different:

d = {'a':123,'b':345} #Declaring a dictionary with 'a','b' as keys and 123, 345 as values

d['a'] #returns 123

d.items() #gives details about items in dict

d.keys() #'a', 'b' are returned. Returns key values in dict 

#Explore other options of dictionary - pop, popitem, get, update, fromkey, etc.

d2 = {'a':[1,2,3], 'b':'Vijay'} #Dictionary with different type of objects. 'a' has list and 'b' has string

type(d2['a']) #list

d2['a'][1] #returns number 2

nested_dict = {'key1':{'key2_in':['abc',100,'def',34]}} #nested dictionary

#accessing items within a nested dictionary
nested_dict['key1']['key2_in'][1] #returns 100


Tuples


Tuples are similar to lists - they are a collection of python objects, separated by commas. They are similar in indexing, nested objects, repetition, etc. However, one thing that distinguishes them from lists is the fact that they are immutable.

tupe = (1,2,3,4,3,1) #assigning tuple

tupe #displays (1,2,3,4,3,1)

tupe[0] #displays '1'

tupe.index(3) #returns 2

tupe.count(4) #Number of times the number 4 occurs in tuple - 1

tupe[2] = 100 #Errors out. Tuples are immutable

tupe_new = (100,200,['a','b'],400) #tuple with combination of items

tupe_new[2][1] #returns 'b'


Tuple unpacking


To extract and utilize individual elements in tuple, we have to do something called 'tuple unpacking'. It is a pretty straight-forward process:

#Declare new tuple containing even more tuples
unpack = ((123,345),(100,200),(3000,4000))

#Regular for loop, looping through the items of tuple
for (a,b) in unpack:
    print (a,b)

#This prints out
############
# 123 345
# 100 200
# 3000 4000

Another example to demonstrate extracting individual elements:

#Declare new tuple containing even more tuples
unpack = ((123,345),(100,200),(3000,4000))

#Regular for loop, looping through the items of tuple
#Print only one of the item
for (a,b) in unpack:
    print (b)

#This prints out
############
# 345
# 200
# 4000


Sets


set_a  = {1,2,3,3,1} #Assign and create new set

set_a #Gives you output of {1,2,3}. Removes duplicates

set_new = {1,3,7,2,1,2,2} #New set

set_new #Prints out {1,2,3,7} - the elements will be in order and unique

set_b = {2,3,5}

set_a - set_b #{1} is the answer

set_a.add(100) #Adds new element

set_a.intersection(set_b) #{2,3}

set_a.union(set_b)

#Explore other set operations

No comments:

Post a Comment