Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

UNIT III

List, Tuples, Set and Dictionaries

Python List: Introduction, accessing List, List operations, Working with Lists, List functions and
methods Python Tuple:- Introduction, accessing Tuple, operations on Tuple, Working with Tuple
,Functions and Methods, Python Set - Introduction, accessing Set, Set operations, working with
Set, Functions and Methods, Python Dictionaries – Introduction, working with dictionaries,
Properties, Functions. Dictionaries Operations, List Comprehension.

Python Dictionaries: Dictionary is a Data Structure in which we can store values as a pair of
key and value. Each key is separated from its value by a colon(:), and consecutive items are
separated by commas. The entire items in a dictionary are enclosed in curly brackets { }. The
syntax for defining a dictionary is:

Dictionary_name = {kaey1:value1,key2:value2,……}

keys in the dictionary must be unique and be of any immutable data type, there is no stringent
requirement for uniqueness and type of values. That is value of a key can be of any type.
Dictionaries are not sequence, rather they are mapping. Mappings are collections of objects that
store objects by key instead of by relative position.

Creating a Dictionary: The empty dictionary is as follows:

# Creating Empty Dictonary

dic = {}

print("Dictonary = ",dic)

# Creating Dictonary With Three Values

dic1 = {'HTNO':'2103A5','Name':'Ravi','Course':'B.Tech C.S.E.'}

print("Empty Dictionay dic1 = ",dic1)

# Creating Dictonary Usin dict() Function

dic2 = dict([('HTNO','2103A5'),('Name','Ravi'),('Course','B.Tech C.S.E.')])

print("Dictonary dic2 = ",dic2)

# Creating Dictionay With 10 Keys

Dic = { x : 2*x for x in range(1,11)}

print("Dictionary Dic = ",Dic)


Output:

>>> %Run 'Creating Dictoary.py'

Empty Dictonary = {}

Dictionay dic1 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.'}

Dictonary dic2 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.'}

Dictionary Dic = {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20}

Access Values: To access values in a Dictionary, square brackets are used along with the key to
obtain the value.

To add a new entry or a key value pair in a dictionary just specify key value pair as an existing
key value pair. To modify an entry, just overwrite the existing value.

# Dictonary With Three Values

dic1 = {'HTNO':'2103A5','Name':'Ravi','Course':'B.Tech C.S.E.'}

dic2 = {'HTNO':'2103A4','Name':'Kumar','Course':'B.Tech E.C.E.'}

print("Dictionary1 = ",dic1)

print("Dictionary2 = ",dic2)

print("HTNO in Dic1 = ",dic1['HTNO'])

print("Name in Dic1 = ",dic1['Name'])

print("Course in Dic2 = ",dic2['Course'])

# Adding New Entries in dic1,dic2

dic1['Year'] = dic2['Year'] = 'Ist year'

dic1['Semester'] = dic2['Semester'] = 'IInd Semester'

print("After Updation Dictionary1 = ",dic1)

print("After Updation Dictionary2 = ",dic2)

#Modifying course entry in dic2

dic2['Course'] = 'B.Tech C.S.E.'

print("After Modification Dictionary2 = ",dic2)


#Looping in Dictionay

print("Looping in Dictionary1")

print("Keys : ",end = " ")

for key in dic1:

print(key, end = ' | ') # accessing only keys

print("\nValues :",end = " ")

for value in dic1.values():

print(value,end = " | ") # Accessing Values

#Accessing Key and Values in Dictionary

print("\nDictionary1 : ",end = ' ')

for key,value in dic1.items():

print(key,value, "\t", end = ' ')

print("\nDictionary2 : ",end = ' ')

for key,value in dic2.items():

print(key,value, "\t", end = ' ')

Output:

>>> %Run 'Access Values in Dictionary.py'

Dictionary1 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.'}

Dictionary2 = {'HTNO': '2103A4', 'Name': 'Kumar', 'Course': 'B.Tech E.C.E.'}

HTNO in Dic1 = 2103A5

Name in Dic1 = Ravi

Course in Dic2 = B.Tech E.C.E.

After Updation Dictionary1 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.',
'Year': 'Ist year', 'Semester': 'IInd Semester'}

After Updation Dictionary2 = {'HTNO': '2103A4', 'Name': 'Kumar', 'Course': 'B.Tech E.C.E.',
'Year': 'Ist year', 'Semester': 'IInd Semester'}
After Modification Dictionary2 = {'HTNO': '2103A4', 'Name': 'Kumar', 'Course': 'B.Tech
C.S.E.', 'Year': 'Ist year', 'Semester': 'IInd Semester'}

Looping in Dictionary1

Keys : HTNO | Name | Course | Year | Semester |

Values : 2103A5 | Ravi | B.Tech C.S.E. | Ist year | IInd Semester |

Dictionary1 : HTNO 2103A5 Name Ravi Course B.Tech C.S.E. Year Ist year
Semester IInd Semester

Dictionary2 : HTNO 2103A4 Name Kumar Course B.Tech C.S.E. Year Ist year
Semester IInd Semester

Deleting Items: we can delete one or more items using the del keyword. To delete or remove all
items using clear() function. Finally we can remove an entire Dictonary from memory again
using del with Dictionary name. the pop() method removes an item from the dictionary and
returns its value, if the key is present. Otherwise KeyError Occurs.

The keys() Method of Dictionary returns a list of all the keys used in the dictionary in an
arbitrary order. The sorted() function is used to sort the keys in sorted order.

print("Example of Delete / Remove Items in Dictionaries")

# Two Dictonaries With Three Values

dic1 = {'HTNO':'2103A5','Name':'Ravi','Course':'B.Tech C.S.E.'}

dic2 = {'HTNO':'2103A4','Name':'Kumar','Course':'B.Tech E.C.E.'}

print("Dictionary1 = ",dic1)

print("After Sorting Keys in Sorted Order Dictionary1 = ",sorted(dic1.keys()))

del(dic1['Course'])

print("After Deleting Course Entry in Dictionary1 = ",dic1)

dic1.pop('Name')

print("After Pop Method Removing Name Entry in Dictionary1 = ",dic1)

#delete all items in Dictionary2

print("Dictionay2 = ",dic2)

dic2.clear()
print("After Clear() Function Diction2 = ",dic2)

#deleting Completely Dictionary2 from memory

del dic2

# Gets Error because afte completely deleted we are calling Dictionary

print("Now, Dictionary2 = ",dic2)

Output:

>>> %Run 'Delete Items.py'

Example of Delete / Remove Items in Dictionaries

Dictionary1 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.'}

After Sorting Keys in Sorted Order Dictionary1 = ['Course', 'HTNO', 'Name']

After Deleting Course Entry in Dictionary1 = {'HTNO': '2103A5', 'Name': 'Ravi'}

After Pop Method Removing Name Entry in Dictionary1 = {'HTNO': '2103A5'}

Dictionay2 = {'HTNO': '2103A4', 'Name': 'Kumar', 'Course': 'B.Tech E.C.E.'}

After Clear() Function Diction2 = {}

Traceback (most recent call last):

File "E:\APTT\Programs\Unit III\Dictonaries\Delete Items.py", line 17, in <module>

print("Now, Dictionary2 = ",dic2)

NameError: name 'dic2' is not defined

Built-in Dictionary Functions and Methods:

SNo Operation Description


1. len(Dict) Returns the length of the Dictionary. That is
the number of items (key value pairs)
2. str(Dict) Returns a String representation of the
Dictionary
3. Dict.clear() Deletes all Entries in the Dictionary
4. Dict.copy() Returns a shallow copy of the Dictionary.
i.e., the dictionary returned will not have a
duplicate copy of Dict but will have the
same reference
5. Dict.fromkeys(seq[,val]) Create a new dictionary with keys from seq
and values set to val. If no val is specified
then, None is assigned as default value
6. Dict.get(key) Returns the value for the key passed as
argument. If the key is not present in
dictionary. It will return the default value. If
no default value is specified then it will
return None
7. Dict.has_key(key) Returns True if the key is present in the
dictionary and False otherwise
8. Dict.items() Returns a list of tuples(key-value pairs)
9. Dict.keys() Returns a list of keys in the dictionary
10. Dict.setdefaultkey,value) Sets a default value for a key that is not
present in the dictionary
11. Dict1.update(Dict2) Adds the key-value pairs of Dict2 to the
key-value pairs of Dict1
12. Dict.values() Returns a list of values in Dictionary
13. Dict.iteritems() Used to iterate throught items in the
dictionary
14. in and not in Checks whether a given key is present in the
dictionary or not

print("Example of Functions and Methods of Dictionary")

print("1. Dict.fromkeys() function")

subjects = ['CSA','C++','DS','OS']

marks = dict.fromkeys(subjects,-1)

print(marks)

print("2.Dict.get(key) Method()")

dic1 = {'HTNO':'2103A5','Name':'Ravi','Course':'B.Tech C.S.E.','Year':''}

print("Dictionary1 = ",dic1)

print("Name Key Value in Dictionary1 = ",dic1.get('Name'))

print("Year Key Value in Dictionary1 = ",dic1.get('Year'))

print("Semester Key Value in Dictionary1 = ",dic1.get('Semester'))

print("3. Dict.has_key(key) Method")

print("Year Key is Present in Dictionary1 = ",'Year' in dic1)


print("Semester Key is Present in Dictionary1 = ",'Semester' in dic1)

print("4. Dict.Items() Method")

print("Items in Dictionary1 = ",dic1.items())

Output:

>>> %Run 'Functions and Methods of Dictionary.py'

Example of Functions and Methods of Dictionary

1. Dict.fromkeys() function

{'CSA': -1, 'C++': -1, 'DS': -1, 'OS': -1}

2.Dict.get(key) Method()

Dictionary1 = {'HTNO': '2103A5', 'Name': 'Ravi', 'Course': 'B.Tech C.S.E.', 'Year': ''}

Name Key Value in Dictionary1 = Ravi

Year Key Value in Dictionary1 =

Semester Key Value in Dictionary1 = None

3. Dict.has_key(key) Method

Year Key is Present in Dictionary1 = True

Semester Key is Present in Dictionary1 = False

4. Dict.Items() Method

Items in Dictionary1 = dict_items([('HTNO', '2103A5'), ('Name', 'Ravi'), ('Course', 'B.Tech


C.S.E.'), ('Year', '')])

You might also like