Lecture

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

Python Programming

Dictionaries and Tuples


Creating Dictionaries
 A dictionary is a collection of an unordered set of key:value pairs, with
the requirement that the keys are unique within a dictionary.
 Dictionaries are constructed using curly braces { }, wherein you include
a list of key:value pairs separated by commas.
 Also, there is a colon (:) separating each of these key and value pairs,
where the words to the left of the colon operator are the keys and the
words to the right of the colon operator are the values.
 Unlike lists, which are indexed by a range of numbers, dictionaries are
indexed by keys. Here a key along with its associated value is called a
key:value pair.
 Dictionary keys are case sensitive.
Creating Dictionaries
 The syntax for creating a dictionary is,

 For example,
>>> fish = {"g": "goldfish", "s":"shark", "n": "needlefish",
"b":"barramundi","m":"mackerel"}
>>> fish
{'g': 'goldfish', 's': 'shark', 'n': 'needlefish', 'b': 'barramundi', 'm': 'mackerel'}
 In dictionaries, the keys and their associated values can be of different types.
>>> mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
>>> mixed_dict
{'portable': 'laptop', 9: 11, 7: 'julius'}
 You can create an empty dictionary by specifying a pair of curly braces and
without any key:value pairs.
 The syntax is, dictionary_name = { }
Accessing and modifying key:value pairs in dictionary
 Each individual key:value pair in a dictionary can be accessed through keys
by specifying it inside square brackets.
 The key provided within the square brackets indicates the key:value pair
being accessed.
 The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]
 The syntax for modifying the value of an existing key or for adding a new
key:value pair to a dictionary is,
dictionary_name[key] = value
 If the key is already present in the dictionary, then the key gets updated
with the new value.
 If the key is not present then the new key:value pair gets added to the
dictionary
Accessing and modifying key:value pairs in dictionary
The dict() function
 The built-in dict() function is used to create dictionary. The syntax for dict()
function when the optional keyword arguments used is,
dict([**kwarg])
The function dict() returns a new dictionary initialized from an optional
keyword arguments and a possibly empty set of keyword arguments.
If no keyword argument is given, an empty dictionary is created.
If keyword arguments are given, the keyword arguments and their values of
the form kwarg = value are added to the dictionary as key:value pairs.
For example,
>>> numbers = dict(one=1, two=2, three=3)
>>> numbers
{'one': 1, 'two': 2, 'three': 3
The built-in Functions used in dictionaries
 There are many built-in functions for which a dictionary can be passed as
an argument .
 The main operations on a dictionary are storing a value with some key and
extracting the value for a given key
Dictionary Methods
 Dictionary allows you to store data in key:value format without depending on indexing.
 You can get a list of all the methods associated with dict by passing the dict function to dir().
Dictionary Methods
Populating dictionaries with key:value pairs
One of the common ways of populating dictionaries is to start with an empty
dictionary { }, then use the update() method to assign a value to the key using
assignment operator.
 If the key does not exist, then the key:value pairs will be created automatically
and added to the dictionary.
For example,
>>> countries = {}
>>> countries.update({"Asia":"India"})
>>> countries.update({"Europe":"Germany"})
>>> countries.update({"Africa":"Sudan"})
>>> countries
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}
Dictionary Methods
Traversing of dictionaries
A for loop can be used to iterate over keys or values or key:value pairs in
dictionaries.
If you iterate over a dictionary using a for loop, then, by default, you will
iterate over the keys.
If you want to iterate over the values, use values() method and for iterating
over the key:value pairs, specify the dictionary’s items() method explicitly.
The dict_keys, dict_values, and dict_items data types returned by dictionary
methods can be used in for loops to iterate over the keys or values or key:value
pairs.
The del statement
 To delete the key:value pair, use the del statement followed by the name
of the dictionary along with the key you want to delete.
del dict_name[key]
 For Example
>>> animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
>>> animals
{'r': 'raccoon', 'c': 'cougar', 'm': 'moose'}
>>> del animals["c"]
>>> animals
{'r': 'raccoon', 'm': 'moose'}
Creating Tuples
 A tuple is a finite ordered list of values of possibly different types which is
used to bundle related values together without having to create a specific type
to hold them.
 Tuples are immutable. Once a tuple is created, you cannot change its values.
 A tuple is defined by putting a comma-separated list of values inside
parentheses ( ). Each value inside a tuple is called an item.
 The syntax for creating tuples is,

 For example,
>>> internet = ("cern", "timbernerslee", "www", 1980)
>>> internet
('cern', 'timbernerslee,' 'www', 1980)
>>> type(internet)
<class 'tuple'>
Creating Tuples
 You can create an empty tuple without any values.
 The syntax is, tuple_name = ()
 For example,
>>> empty_tuple = ()
>>> empty_tuple
()
>>> type(empty_tuple)
<class ‘tuple’>
 You can store any item of type string, number, object, another variable, and even
another tuple itself.
 You can have a mix of different types of items in tuples, and they need not be
homogeneous
 For example,
>>> air_force = ("f15", "f22a", "f35a")
>>> fighter_jets = (1988, 2005, 2016, air_force)
>>> fighter_jets
(1988, 2005, 2016, ('f15', 'f22a', 'f35a'))
>>> type(fighter_jets)
<class 'tuple'>
Basic Tuple Operation
Like in lists, you can use the + operator to concatenate tuples together and the *
operator to repeat a sequence of tuple items.
 For example,
>>> tuple_1 = (2, 0, 1, 4)
>>> tuple_2 = (2, 0, 1, 9)
>>> tuple_1 + tuple_2
(2, 0, 1, 4, 2, 0, 1, 9)
>>> tuple_1 * 3
(2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)
>>> tuple_1 == tuple_2
False

 You can check for the presence of an item in a tuple using in and not in membership
operators. It returns a Boolean True or False.
 For example,
>>> tuple_items = (1, 9, 8, 8)
>>> 1 in tuple_items
True
>>> 25 in tuple_items
False

 Comparison operators like <, <=, >, >=, == and != are used to compare tuples.
 For example,
>>> tuple_1 = (9, 8, 7)
>>> tuple_2 = (9, 1, 1)
>>> tuple_1 > tuple_2
True
>>> tuple_1 != tuple_2
Basic Tuple Operation
The tuple() function
The built-in tuple() function is used to create a tuple.
 The syntax for the tuple() function is,
tuple([sequence])
where the sequence can be a number, string or tuple itself.
If the optional sequence is not specified, then an empty tuple is created.
>>> norse = "vikings"
>>> string_to_tuple = tuple(norse)
>>> string_to_tuple
('v', 'i', 'k', 'i', 'n', 'g', 's')
>>> zeus = ["g", "o", "d", "o", "f", "s", "k", "y"]
>>> list_to_tuple = tuple(zeus)
>>> list_to_tuple
('g', 'o', 'd', 'o', 'f', 's', 'k', 'y')
Indexing and Slicing In Tuples
 Each item in a tuple can be called individually through indexing.
 The expression inside the bracket is called the index. Square brackets [ ] are
used by tuples to access individual items, with the first item at index 0, the
second item at index 1 and so on.
 The index provided within the square brackets indicates the value being
accessed.
 The syntax for accessing an item in a tuple is,
tuple_name[index]
 where index should always be an integer value and indicates the item to be
selected. For the tuple holy_places, the index breakdown is shown below

>>> holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib",


"bethlehem", "mahabodhi")
>>> holy_places
('jerusalem', 'kashivishwanath', 'harmandirsahib', 'bethlehem',
'mahabodhi')
Indexing and Slicing In Tuples
 Slicing of tuples is allowed in Python wherein a part of the tuple can be
extracted by specifying an index range along with the colon (:) operator,
which itself results as tuple type.
 The syntax for tuple slicing is
 where both start and stop are integer values (positive or negative values).
 Tuple slicing returns a part of the tuple from the start index value to stop
index value, which includes the start index value but excludes the stop index
value.
 The step specifies the increment value to slice by and it is optional
 For the tuple colors, the positive and negative index breakdown is shown below.
 For example,
>>> colors = ("v", "i", "b", "g", "y", "o", "r")
>>> colors
('v', 'i', 'b', 'g', 'y', 'o', 'r')
Built-In Functions using In Tuples

For example,
>>> years = (1987, 1985, 1981, 1996)
>>> len(years)
4
>>> sum(years)
7949
>>> sorted_years = sorted(years)
>>> sorted_years
[1981, 1985, 1987, 1996]
Relations between Tuples and List
 Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
 Tuples are immutable, and usually, contain a heterogeneous sequence of
elements that are accessed via unpacking or indexing.
 Lists are mutable, and their items are accessed via indexing. Items cannot be
added, removed or replaced in a tuple.
 For example,
>>> coral_reef = ("great_barrier", "ningaloo_coast", "amazon_reef", "pickles_reef")
>>> coral_reef[0] = "pickles_reef"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> coral_reef_list = list(coral_reef)
>>> coral_reef_list
['great_barrier', 'ningaloo_coast', 'amazon_reef', 'pickles_reef']
Relations between Tuples and Dictionary
 Tuples can be used as key:value pairs to build dictionaries.
 For example,
>>> fish_weight_kg = (("white_shark", 520), ("beluga", 1571), ("greenland_shark",1400))
>>> fish_weight_kg_dict = dict(fish_weight_kg)
>>> fish_weight_kg_dict
{'white_shark': 520, 'beluga': 1571, 'greenland_shark': 1400}

 The method items() in a dictionary returns a list of tuples where each tuple
corresponds to a key:value pair of the dictionary.
 For example,
>>> founding_year = {"Google":1996, "Apple":1976, "Sony":1946, "ebay":1995, "IBM":1911}
>>> founding_year.items()
dict_items([('Google', 1996), ('Apple', 1976), ('Sony', 1946), ('ebay', 1995), ('IBM',
1911)])
>>> for company, year in founding_year.items():
... print(f"{company} was found in the year {year}")
Tuple Methods
 You can get a list of all the methods associated with the tuple) by passing the
tuple function to dir().

 For example,
>>> channels = ("ngc", "discovery", "animal_planet", "history", "ngc")
>>> channels.count("ngc")
2
>>> channels.index("history")
3
Tuple Methods
Tuple Packing and Unpacking
The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
>>> t = 12345, 54321, 'hello!'
>>> t
(12345, 54321, 'hello!')
The values 12345, 54321 and 'hello!' are packed together into a tuple
The reverse operation of tuple packing is also possible. For example,
>>> x, y, z = t
>>> x
12345
>>> y
54321
>>> z
'hello!
Traversing the Tuples
You can iterate through each item in tuples using for loop
Populating Tuples with Items
You can populate tuples with items using += operator and also by converting
list items to tuple items
The zip() function
 The zip() function makes a sequence that aggregates elements from each of the
iterables (can be zero or more).
 The syntax for zip() function is, zip(*iterables)
 An iterable can be a list, string, or dictionary. It returns a sequence of tuples, where
the i-th tuple contains the i-th element from each of the iterables.
 The aggregation of elements stops when the shortest input iterable is exhausted.
For example, if you pass two iterables with one containing two items and other
containing five items, then the zip() function returns a sequence of two tuples.
 With a single iterable argument, it returns an iterator of one tuple. With no
arguments, it returns an empty iterator.
 For example,
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
Sets
 Python also includes a data type for sets. A set is an unordered collection
with no duplicate items.
 Primary uses of sets include membership testing and eliminating duplicate
entries.
 Sets also support mathematical operations, such as union, intersection,
difference, and symmetric difference.
 Curly braces { } or the set() function can be used to create sets with a
comma-separated list of items inside curly brackets { }.
 Note: to create an empty set you have to use set() and not { } as the latter
creates an empty dictionary
Set Methods
 You can get a list of all the methods associated with the set by passing the set
function to dir()
Frozenset
 A frozenset is basically the same as a set, except that it is immutable.
 Once a frozenset is created, then its items cannot be changed.
 Since they are immutable, they can be used as members in other sets and as
dictionary keys.
 The frozensets have the same functions as normal sets, except none of the
functions that change the contents (update, remove, pop, etc.) are available.
 For example,
>>> fs = frozenset(["g", "o", "o", "d"])
>>> fs
frozenset({'d', 'o', 'g'})
>>> animals = set([fs, "cattle", "horse"])
>>> animals
{'cattle', frozenset({'d', 'o', 'g'}), 'horse'}
>>> official_languages_world = {"english":59, "french":29, "spanish":21}
>>> frozenset(official_languages_world)
frozenset({'spanish', 'french', 'english'})

You might also like