Dictionary Tuples Functions
Dictionary Tuples Functions
Dictionaries
Introduction
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered, changeable and do not
allow duplicates.
• Dictionaries are written with curly brackets, and have keys and
values:
Example: Output:
Dictionary Items
Example: Output:
Dictionary Basics
d1 = {} Empty dictionary
d2 = {‘spam’ : 2, ‘eggs’ : 3} Two-item dictionary
d3 = {‘food’ : {‘ham’ : 1, ‘egg’ : 2}} Nesting
d2[‘eggs’], d3[‘food’][‘ham’] Indexing by key
d2.keys(), d2.values() Methods: membership test, keys list, values
list, etc.
len(d1) Length (number stored entries)
d2[key] = new, del d2[key] Adding/changing, deleting
Dictionaries Basics
Comparing Lists and Dictionaries
Dictionaries are like lists except that they use keys instead of positions to look up values
Dept. of ISE 5
Basic operations
Dept. of ISE 6
Dictionary properties
•They are mutable.
•They do not allow duplicates to be stored.
•The keys and values can be of any data type.
•The keys are always unique.
Dictionary
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered.
When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an
item by using an index.
Dictionary …
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
To determine how many items a dictionary has, use the len() function:
Print the number of items in the dictionary:
Dictionary Items - with Data Types
The function dict creates a new dictionary with no items. Because dict is the
name of a built-in function, you should avoid using it as a variable name.
The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets:
Different ways of creating a dictionary
Access Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
There is also a method called get() that will give you the same result:
Get keys, Get values from a dictionary
in operator
The in operator works on dictionaries; it tells you whether something
appears as a key in the dictionary (appearing as a value is not good
enough).
We will write a Python program to read through the lines of the file, break each line
into a list of words, and then loop through each of the words in the line and count
each word using a dictionary.
Write a program to count the occurrence of words in a file with some written text
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
Looping and dictionaries
If you use a dictionary as the sequence in a for statement, it traverses
the keys of the dictionary.
This loop prints each key and the corresponding value:
Output:
chuck 1
annie 42
jan 100
Loop Through a Dictionary
Print all key names in the dictionary, one by one:
Print all values in the dictionary, one by one:
We can also use the values() function to return values
of a dictionary:
Loop through both keys and values, by using the
items() function
For example, if we wanted to find all the entries in a dictionary
with a value above ten, we could write the following code:
Write a python code to print the keys in alphabetical order.
To print the keys in alphabetical order, you first make a list of the keys in the dictionary
using the keys method available in dictionary objects, and then sort that list and loop
through the sorted list, looking up each key and printing out key-value pairs in sorted order.
Advanced text parsing
import string
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
# First two parameters are empty strings
line = line.translate(line.maketrans("", "", string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
Advanced text parsing(Contd.)
Input File: romeo.txt
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
Output:
Advanced text parsing(Contd.)
● Since the Python split function looks for spaces and treats words as tokens separated by
spaces, we would treat the words “soft!” and “soft” as different words and create a
separate dictionary entry for each word.
● Also since the file has capitalization, we would treat “who” and “Who” as different words
with different counts.
● We can solve both these problems by using the string methods lower, punctuation, and
translate.
● The translate is the most subtle of the methods.
○ line.translate(str.maketrans(fromstr, tostr, deletestr))
● Replace the characters in fromstr with the character in the same position in tostr and
delete all characters that are in deletestr.
● The fromstr and tostr can be empty strings and the deletestr parameter can be omitted.
● We will use the deletechars parameter to delete all of the punctuation.
● To know the list of characters that Python considers “punctuation”
>>> import string Output:
>>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Lab programs on Dictionary
1. Write a program to count the numbers of occurrence of each character in the string and
store them in a dictionary data structure.
2. Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.
3. Write a program that combines two lists into a dictionary.
Lab programs on Dictionary
Write a program to use split and join methods in the string and trace a birthday with a dictionary data structure.
Lab programs on Dictionary
Write a program that combines two lists into a dictionary.
if len(keys) != len(values):
print("The two lists must have the same length.")
else:
combined_dict = {}
for i in range(len(keys)):
combined_dict[keys[i]] = values[i]
print(combined_dict)
Lab programs on Dictionary
Write a program that combines two lists into a dictionary.
# Two lists to combine into a dictionary
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
combined_dict = {}
for i in range(len(keys)):
combined_dict[keys[i]] = values[i]
{'P': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}
Programs
Write a program to find the sum and average of dictionary values.
In a class of 10 students, it is required to store the marks scored along
with their USNs. Use an appropriate data structure to store the marks.
Also, retrieve the students who have scored marks above average.
Given a list of names, create a dictionary with key as a starting letter and
value as all names starting with that letter.
Merge the contents of 2 dictionaries.
Sort the elements in the dictionary based on the keys.
Add a key value pair at the beginning of the given dictionary.
Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are the square of the
keys.
Programs
1. Add a key value pair at the beginning of the given dictionary
d1={'name':'John','Dept':'Advertising','salary':50000}
key=input("Enter the key to be added ")
value=input("Enter the value ")
d2={}
d2[key]=value
for key in d1: Enter the key to be added place
d2[key]=d1[key] Enter the value Bengaluru
print(d2) {'place': 'Bengaluru', 'name': 'John', 'Dept': 'Advertising', 'salary': 50000}
Programs
Merge the contents of 2 dictionaries.
Programs
Sort the elements in the dictionary based on the keys
myKeys = list(myDict.keys())
myKeys.sort()
sorted_dict=dict()
print(sorted_dict)
Programs
Write a program to find the sum and average of dictionary values
data = { "key1": 10, "key2": 20, "key3": 30,
"key4": 40}
values_sum = sum(data.values())
d = dict()
for x in range(1, 11):
d[x] = x ** 2
print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Write a Python script to print a dictionary where the keys are based on the length of the strings from the list.
l1=['anuj','atith','ajith','bhuvi','dhruv','Vani','Rani','Rajeshwari']
d={}
for name in l1:
length=len(name)
if length not in d:
d[length]=[]
d[length].append(name)
print(d)
{4: ['anuj', 'Vani', 'Rani'], 5: ['atith', 'ajith', 'bhuvi', 'dhruv'], 10: ['Rajeshwari']}
Chapter 2: Tuples
Tuples
•Tuples are a sequence of values separated by commas.
•The values stored in the tuple can be of any type.
•They can be indexed by integers just like list.
•Tuples are immutable unlike lists.
•Defining tuples:
t=‘a’,’b’,’c’
or
t=(‘a’,’b’,’c’)
To create a tuple with a single element, you have
to include the final comma:
We can’t modify the elements of a tuple, but we can replace one tuple
with another:
Comparing Tuples
In Python, tuples are compared lexicographically, meaning they are compared element
by element, starting from the first one. When comparing two tuples:
1. Python first compares the first elements of each tuple.
2. If the first elements are equal, it proceeds to compare the second elements.
3. This process continues until a pair of elements is found that is not equal, or one
of the tuples ends.
For example:
Here, the first elements are both 0. Since they are equal, Python
moves to compare the second elements. The second element of
the first tuple, 3, is less than the second element of the second
tuple, 4. Therefore, (0, 3, 4) is considered smaller than (0, 4, 5).
Comparing Tuples …
Here, the first elements are both 0, and the second
● Similarly, elements are 3 and 4, respectively. Since 3 is less
than 4, the first tuple is considered smaller.
For each iteration through the loop, both key and value are advanced to
the next key-value pair in the dictionary.
Sorting the Dictionary by values
Output:
Count the occurrences of words
Given a text file, write a program to count the number of occurrences of
each word in it.
- We make use of string translate(), to remove any punctuation marks in the
text.
- Syntax:
string.translate(table)
- Here, the table is a mapping table, that contains the ‘from’ pattern and the
to ‘pattern’.
- To create this mapping table, we make use of the maketrans() function.
D1= str.maketrans(x, y, z)
- If only one parameter is mentioned, it must be a dictionary containing the
mapping of values.
- If x and y mentioned, the x will be replaced with y.
- z is the value that needs to be deleted from the string.
- Returns a dictionary containing a mapping of key values. Each key will be
replaced with the corresponding value.
Convert tuple into a dictionary
Output:
Remove empty tuple from a list of tuples
Output:
List Tuple
[] ()
Inserting and deleting items is easier with a list. Accessing the elements is best accomplished with a tuple
data type.
Lists consume more memory Tuple consumes less than the list
Lists have several built-in methods. A tuple does not have many built-in methods because of
immutability
A unexpected change or error is more likely to occur in In a tuple, changes and errors don't usually occur
a list because of immutability.
If the content is not fixed keeps on changing, then it is If the content is fixed, then it is better to opt list.
better to opt list Ex: name, usn, emp_id, latitude and longitude of a
Ex: student marks, age, employee salary, weather, location
List Tuple Dictionaries
A list is a non-homogeneous data A Tuple is also a A dictionary is also a non-homogeneous data
structure that stores the elements in non-homogeneous data structure structure that stores key-value pairs.
columns of a single row or multiple that stores elements in columns
rows. of a single row or multiple rows.
The list can be represented by [ ] Tuple can be represented by ( ) The dictionary can be represented by { }
The list allows duplicate elements Tuple allows duplicate elements The dictionary doesn’t allow duplicate keys.
Example: [1, 2, 3, 4, 5] Example: (1, 2, 3, 4, 5) Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}
A list can be created using the list() Tuple can be created using the A dictionary can be created using the dict()
function tuple() function. function.
A list is mutable i.e we can make any A tuple is immutable i.e we can A dictionary is mutable, ut Keys are not
changes in the list. not make any changes in the duplicated.
tuple.
List is ordered Tuple is ordered Dictionary is ordered (Python 3.7 and above)
print(updated_tuple)
Programs
Write a Python program to convert a tuple to a string.
original_tuple = ('a', 'b', 'c', 'd', 'e') tup = ('h', 'e', 'l', 'l', 'o')
str = ''
tuple_string = ''.join(original_tuple) for item in tup:
str = str + item
print(tuple_string) print(str)
Programs
Write a Python program to get the 4th element and 4th element from last of a tuple.
sample_tuple = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
fourth_ele = sample_tuple[3]
fourth_from_last = sample_tuple[-4]
item_counts = {}
repeated_items = []
for item, count in item_counts.items():
if count > 1:
repeated_items.append(item)
if check in tuple:
print("The element exists in the tuple.")
else:
print("The element does not exist in the tuple.")
('w', 'a', 'r', 's', 'o', 'u', 'r', 'c', 's') ('w', 'a', 'r', 's', 'o', 'u', 'r', 'c', 's')
element not found element found at index: 3
Programs : Write a Python program to find the index of an item of a tuple
Tuple =( 1, 0, 4, 2, 5, 6, 7, 5) sample_tuple = (90, 70, 50, 20, 50)
print(len(Tuple)) length = 0
for item in sample_tuple:
length += 1
Example:
Output:
import random 0.35049533360156915
for i in range(10): 0.21611787782104575
0.37947439590473364
x = random.random() 0.27303912066907343
print(x) 0.9734623420745635
0.22753483960775467
0.6689999577883523
0.6448529221258081
0.7170635550607704
0.3191037057631271
Random numbers (contd..)
The function randint takes the parameters low and high, and returns
an integer between low and high (including both).
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
Random numbers (contd..)
To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
Math functions
• Python has a math module that provides most of the familiar
mathematical functions.
• Before we can use the module, we have to import it:
>>> import math
>>> math.sqrt(2) / 2.0
0.7071067811865476
Adding new functions
• A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
• Once we define a function, we can reuse the function over and over
throughout our program.
• We create a new function using the def keyword followed by
optional parameters in parentheses
• We indent the body of the function
• This defines the function but does not execute the body of the
function
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
• This is the store and reuse pattern
Flow of execution
• In order to ensure that a function is defined before its first use, we
have to know the order in which statements are executed, which is
called the flow of execution.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
Flow of execution
• When the function greet() is called, the program's control transfers
to the function definition.
• All the code inside the function is executed.
• The control of the program jumps to the next statement after the
function call.
Arguments
• An argument is a value we pass into the function as its input when
we call the function
• We use arguments so we can direct the function to do different
kinds of work when we call it at different times
• We put the arguments in parentheses after the name of the
function
Functions
Parameters
A parameter is a variable which we use in the function definition. It is a
“handle” that allows the code in the function to access the arguments for
a particular function invocation.
def greet(lang):
if lang == ‘hi':
print(‘Namaste')
elif lang == ‘kn':
print(‘Namaskara')
else:
print('Hello')
>>> greet(‘kn')
Namaskara
>>> greet(‘en')
Hello
>>> greet(‘hi')
Namaste
Arguments and Parameters in Python
• Both arguments and parameters are variables/ constants passed into a function.
The difference is that:
• Arguments are the variables passed to the function in the function call.
• Parameters are the variables used in the function definition.
• The number of arguments and parameters should always be equal except for the
variable length argument list.
def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
• (num1, num2) are in the function call, and (a, b) are in the function definition.
• (num1, num2) are arguments and (a, b) are parameters.
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the calling
expression. The return keyword is used for this.
Example:
def greet():
return "Hello"
Example:
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
Output: 8
Void functions
Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to assign
the result to a variable, you get a special value called None.
Example:
def addtwo(a, b):
added = a + b
print(added)
addtwo(3, 5) #output: 8
a=addtwo(3,5)
print(a) #output: None
Why functions
Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read,
understand, and debug.
Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have to make it in one
place.
Dividing a long program into functions allows you to debug the parts
one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.
Function Reusability
We reuse the function written in one program in another program.
import calc
first = list.pop(0)
last = list.pop(-1)
temp = List1[0] list.insert(0, last)
list.append(first)
List1[0] = List1[size - 1] return list
List1[size - 1] = temp li = [1, 9, 2, 10, 19, 30]
print(li)
print("Swapped list: ",swapList(li))
return List1
l1=[1,2,3,4]
l2=[5,6,7,8]
add_lists(l1,l2)
print("Resulting list is:",l1)
Function to print upper and lower case(count)
def case_letter(s):
c1=0
c2=0
for c in s:
if c>='A' and c<='Z':
c1+=1
elif c>='a' and c<='z':
c2+=1
return c1,c2
s1="Welcome to BMSCE"
c1,c2=case_letter(s1)
print("Uppercase:",c1,"lowercase:",c2)
Assignment
Function to find factorial of a number
def factorial(n):
def factorial(n):
if n < 0: res = 1
return 0 for i in range(2, n+1):
elif n == 0 or n == 1: res *= i
return 1 return res
else: # Driver Code
num = 5
fact = 1 print("Factorial of", num,
while(n > 1): "is",factorial(num))
fact *= n
n -= 1
return fact
num = 5
print("Factorial of",num,"is",
factorial(num))
Function to check prime or not
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check for factors from 3 to sqrt(n)
for i in range(3, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
number = 29
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Function to Check if a String is Palindrome or Not
def isPalindrome(s): def isPalindrome(x):
return s == s[::-1] w = ""
for i in x:
w=i+w
s = "malayalam" if (x == w):
ans = isPalindrome(s) print("Yes")
if ans: else:
print("Yes") print("No")
else: str1 = input("enter a string to check polidrome: ")
isPalindrome(str1)
print("No")
def sort_words(seq):
words = seq.split('-')
words.sort()
sorted_seq = '-'.join(words)
return sorted_seq
print(computegrade(0.95))
print(computegrade(0.85))