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 (20)

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
Groovy
NexThoughts Technologies
 
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
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 
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
 

Similar to Python Lecture 10 (20)

Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Lect - 12 solve d.pptx
Lect - 12 solve                    d.pptxLect - 12 solve                    d.pptx
Lect - 12 solve d.pptx
SumeetRathi5
 
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
 
beginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdfbeginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
MongoDB
MongoDB MongoDB
MongoDB
Hemant Kumar Tiwary
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
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
 
DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...
kavyamp025
 
Untitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptxUntitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
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
 
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptxDAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
collegework11
 
R workshop
R workshopR workshop
R workshop
Revanth19921
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Lect - 12 solve d.pptx
Lect - 12 solve                    d.pptxLect - 12 solve                    d.pptx
Lect - 12 solve d.pptx
SumeetRathi5
 
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
 
beginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdfbeginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
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
 
DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...
kavyamp025
 
Untitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptxUntitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
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
 
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
 
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptxDAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
DAR LEbhsuussbjshsbshshsbsbbbsbsCTURE 3.pptx
collegework11
 

More from Inzamam Baig (11)

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
 

Recently uploaded (20)

Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 
Oedipus The King Student Revision Booklet
Oedipus The King Student Revision BookletOedipus The King Student Revision Booklet
Oedipus The King Student Revision Booklet
jpinnuck
 
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptxQuiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
SouptikUkil
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Flower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdfFlower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdf
kushallamichhame
 
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Rajdeep Bavaliya
 
Sri Guru Arjun Dev Ji .
Sri Guru Arjun Dev Ji                   .Sri Guru Arjun Dev Ji                   .
Sri Guru Arjun Dev Ji .
Balvir Singh
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18
Celine George
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
Policies, procedures, subject selection and QTAC.pptx
Policies, procedures, subject selection and QTAC.pptxPolicies, procedures, subject selection and QTAC.pptx
Policies, procedures, subject selection and QTAC.pptx
mansk2
 
Order: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptxOrder: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptx
Arshad Shaikh
 
How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18
Celine George
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 
Oedipus The King Student Revision Booklet
Oedipus The King Student Revision BookletOedipus The King Student Revision Booklet
Oedipus The King Student Revision Booklet
jpinnuck
 
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptxQuiz-E-Mataram (Under 20 Quiz Set) .pptx
Quiz-E-Mataram (Under 20 Quiz Set) .pptx
SouptikUkil
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Flower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdfFlower Identification Class-10 by Kushal Lamichhane.pdf
Flower Identification Class-10 by Kushal Lamichhane.pdf
kushallamichhame
 
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...
Rajdeep Bavaliya
 
Sri Guru Arjun Dev Ji .
Sri Guru Arjun Dev Ji                   .Sri Guru Arjun Dev Ji                   .
Sri Guru Arjun Dev Ji .
Balvir Singh
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18How to Setup Renewal of Subscription in Odoo 18
How to Setup Renewal of Subscription in Odoo 18
Celine George
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATIONTHE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
THE CHURCH AND ITS IMPACT: FOSTERING CHRISTIAN EDUCATION
PROF. PAUL ALLIEU KAMARA
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
Policies, procedures, subject selection and QTAC.pptx
Policies, procedures, subject selection and QTAC.pptxPolicies, procedures, subject selection and QTAC.pptx
Policies, procedures, subject selection and QTAC.pptx
mansk2
 
Order: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptxOrder: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptx
Arshad Shaikh
 
How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18How to create and manage blogs in odoo 18
How to create and manage blogs in odoo 18
Celine George
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 

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': '[email protected]'} >>> print(student_info) {'name': 'Adil', 'email': '[email protected]', '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)