SlideShare a Scribd company logo
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 10
Fundamentals of Programming
Dictionaries
A dictionary is like a list, but more general
A dictionary has a mapping between a set of indices (which are
called keys) and a set of values
Each key maps to a value
The association of a key and a value is called a key-value pair or
sometimes an item
In a list, the index positions have to be integers; in a dictionary,
the indices can be (almost) any type
>>> student_info = dict()
>>> student_info = {}
>>> print(student_info)
{}
The curly brackets, {}, represent an empty dictionary
Adding Items to Dictionary
>>> student_info['name'] = 'Adil'
This line creates an item that maps from the key 'name' to the
value “Adil”
>>> print(student_info)
{'name': 'Adil'}
>>> student_info = {'name': 'Adil', 'age': '25', 'email': 'adil@kiu.edu.pk'}
>>> print(student_info)
{'name': 'Adil', 'email': 'adil@kiu.edu.pk', 'age': '25'}
The order of the key-value pairs is not the same
If you type the same example on your computer, you might get a different
result
the order of items in a dictionary is unpredictable
>>> print(student_info['age'])
'25'
The key 'age' always maps to the value “25” so the order of the
items doesn't matter
If the key isn't in the dictionary, you get an exception:
>>> print(student_info['gpa'])
KeyError: 'gpa'
>>> len(student_info)
3
The len function works on dictionaries; it returns the number of
key-value pairs
IN Operator
>>> 'name' in student_info
True
>>> 'Adil' in student_info
False
it tells whether something appears as a key in the dictionary
To see whether something appears as a value in a dictionary, you
can use the method values, which returns the values as a type
that can be converted to a list, and then use the in operator:
>>> vals = list(student_info.values())
>>> 'Adil' in vals
True
The in operator uses different algorithms for lists and dictionaries
For lists, it uses a linear search algorithm
As the list gets longer, the search time gets longer in direct proportion
to the length of the list
For dictionaries, Python uses an algorithm called a hash table that has
a remarkable property: the in operator takes about the same amount
of time no matter how many items there are in a dictionary
Updating a value in dictionary
student_info = {
'name': 'Zeeshan',
'age': 20,
'courses': ['C++','Python','C#']
}
student_info.update({'name': 'Fatima'})
Deleting a key
del student_info['name']
student_age = student_info.pop('age')
Getting Keys and Values
student_info.keys()
student_info.values()
student_info.items()
Looping over a dictionary
for key, values in student_info.items():
print(key, values)
Dictionary as a set of counters
word = 'Department of Computer Science Karakoram International University'
words = {}
for letter in word:
if letter not in words:
words[letter] = 1
else:
words[letter] = words[letter] + 1
print(words)
We are effectively computing a histogram, which is a statistical
term for a set of counters (or frequencies)
get method
Dictionaries have a method called get that takes a key and a
default value
If the key appears in the dictionary, get returns the corresponding
value; otherwise it returns the default value
>>> cs_department = {'cs' : 50, 'gis': 50}
>>> print(cs_department .get('emails', 0))
0
>>> print(cs_department .get('gis', 0))
50
department = 'Department of Computer Science Karakoram International University'
words = dict()
for word in department:
words[word] = words.get(word,0) + 1
print(words)
Dictionaries and files
name of the common uses of a dictionary is to count the
occurrence of words in a file with some written text
file_name = input('Enter the name of the file:')
count_words = {}
try:
with open(file_name) as file_handler:
for line in file_handler:
words_list = line.rstrip().split()
for word in words_list:
if word not in count_words:
count_words[word] = 1
else:
count_words[word] += 1
except:
print('File Not Found')
exit()
assignment_marks = {
'C++': 15,
'Java': 20
}
for key, value in assignment_marks.items():
if assignment_marks[key] > 10 :
print(key, value)
Sorting
assignment_marks = {
'C++': 15,
'Java': 20,
'Python': 18,
'Intro to GIS':19
}
sorted_lst = list(assignment_marks.keys())
print(sorted_lst)
sorted_lst.sort()
for data in sorted_lst:
print(data)
Advanced text parsing
file_name = input('Enter the name of the file:')
words_count = {}
try:
with open(file_name) as file_handler:
for line in file_handler:
line = line.rstrip()
table = line.maketrans('', '', string.punctuation)
line = line.translate(table)
line = line.lower()
words_list = line.split()
for word in words_list:
if word not in words_count:
words_count[word] = 1
else:
words_count[word] += 1
except Exception as e:
print(e)
exit()
print(words_count)

More Related Content

What's hot

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
BMS Institute of Technology and Management
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
S.M. Salaquzzaman
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
Munazza-Mah-Jabeen
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Groovy
GroovyGroovy
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Sets in python
Sets in pythonSets in python
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
delimitry
 

What's hot (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
1. python
1. python1. python
1. python
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
List in Python
List in PythonList in Python
List in Python
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
Python list
Python listPython list
Python list
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Groovy
GroovyGroovy
Groovy
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
 

Similar to Python Lecture 10

DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
Raajendra M
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
MongoDB
MongoDB MongoDB
Python : Functions
Python : FunctionsPython : Functions
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
Shakila Mahjabin
 
UNIT 2 Structured query language commands
UNIT 2 Structured query language commandsUNIT 2 Structured query language commands
UNIT 2 Structured query language commands
Bhakti Pawar
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
R workshop
R workshopR workshop
R workshop
Revanth19921
 
Ch 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptxCh 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
MSB Academy
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
Praveen M Jigajinni
 
Cs341
Cs341Cs341
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 

Similar to Python Lecture 10 (20)

DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
MongoDB
MongoDB MongoDB
MongoDB
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
UNIT 2 Structured query language commands
UNIT 2 Structured query language commandsUNIT 2 Structured query language commands
UNIT 2 Structured query language commands
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
R workshop
R workshopR workshop
R workshop
 
Ch 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptxCh 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptx
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
 
Cs341
Cs341Cs341
Cs341
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 

More from Inzamam Baig

Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
Inzamam Baig
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Inzamam Baig
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
Inzamam Baig
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
Inzamam Baig
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
Inzamam Baig
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
Inzamam Baig
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
Inzamam Baig
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
Inzamam Baig
 

More from Inzamam Baig (11)

Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Recently uploaded

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 

Recently uploaded (20)

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 

Python Lecture 10

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 10 Fundamentals of Programming
  • 2. Dictionaries A dictionary is like a list, but more general A dictionary has a mapping between a set of indices (which are called keys) and a set of values Each key maps to a value The association of a key and a value is called a key-value pair or sometimes an item
  • 3. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type
  • 4. >>> student_info = dict() >>> student_info = {} >>> print(student_info) {} The curly brackets, {}, represent an empty dictionary
  • 5. Adding Items to Dictionary >>> student_info['name'] = 'Adil' This line creates an item that maps from the key 'name' to the value “Adil” >>> print(student_info) {'name': 'Adil'}
  • 6. >>> student_info = {'name': 'Adil', 'age': '25', 'email': 'adil@kiu.edu.pk'} >>> print(student_info) {'name': 'Adil', 'email': 'adil@kiu.edu.pk', 'age': '25'} The order of the key-value pairs is not the same If you type the same example on your computer, you might get a different result the order of items in a dictionary is unpredictable
  • 7. >>> print(student_info['age']) '25' The key 'age' always maps to the value “25” so the order of the items doesn't matter
  • 8. If the key isn't in the dictionary, you get an exception: >>> print(student_info['gpa']) KeyError: 'gpa'
  • 9. >>> len(student_info) 3 The len function works on dictionaries; it returns the number of key-value pairs
  • 10. IN Operator >>> 'name' in student_info True >>> 'Adil' in student_info False it tells whether something appears as a key in the dictionary
  • 11. To see whether something appears as a value in a dictionary, you can use the method values, which returns the values as a type that can be converted to a list, and then use the in operator: >>> vals = list(student_info.values()) >>> 'Adil' in vals True
  • 12. The in operator uses different algorithms for lists and dictionaries For lists, it uses a linear search algorithm As the list gets longer, the search time gets longer in direct proportion to the length of the list For dictionaries, Python uses an algorithm called a hash table that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary
  • 13. Updating a value in dictionary student_info = { 'name': 'Zeeshan', 'age': 20, 'courses': ['C++','Python','C#'] } student_info.update({'name': 'Fatima'})
  • 14. Deleting a key del student_info['name'] student_age = student_info.pop('age')
  • 15. Getting Keys and Values student_info.keys() student_info.values() student_info.items()
  • 16. Looping over a dictionary for key, values in student_info.items(): print(key, values)
  • 17. Dictionary as a set of counters word = 'Department of Computer Science Karakoram International University' words = {} for letter in word: if letter not in words: words[letter] = 1 else: words[letter] = words[letter] + 1 print(words)
  • 18. We are effectively computing a histogram, which is a statistical term for a set of counters (or frequencies)
  • 19. get method Dictionaries have a method called get that takes a key and a default value If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value
  • 20. >>> cs_department = {'cs' : 50, 'gis': 50} >>> print(cs_department .get('emails', 0)) 0 >>> print(cs_department .get('gis', 0)) 50
  • 21. department = 'Department of Computer Science Karakoram International University' words = dict() for word in department: words[word] = words.get(word,0) + 1 print(words)
  • 22. Dictionaries and files name of the common uses of a dictionary is to count the occurrence of words in a file with some written text
  • 23. file_name = input('Enter the name of the file:') count_words = {} try: with open(file_name) as file_handler: for line in file_handler: words_list = line.rstrip().split() for word in words_list: if word not in count_words: count_words[word] = 1 else: count_words[word] += 1 except: print('File Not Found') exit()
  • 24. assignment_marks = { 'C++': 15, 'Java': 20 } for key, value in assignment_marks.items(): if assignment_marks[key] > 10 : print(key, value)
  • 25. Sorting assignment_marks = { 'C++': 15, 'Java': 20, 'Python': 18, 'Intro to GIS':19 } sorted_lst = list(assignment_marks.keys()) print(sorted_lst) sorted_lst.sort() for data in sorted_lst: print(data)
  • 27. file_name = input('Enter the name of the file:') words_count = {} try: with open(file_name) as file_handler: for line in file_handler: line = line.rstrip() table = line.maketrans('', '', string.punctuation) line = line.translate(table) line = line.lower() words_list = line.split() for word in words_list: if word not in words_count: words_count[word] = 1 else: words_count[word] += 1 except Exception as e: print(e) exit() print(words_count)