SlideShare a Scribd company logo
1 of 27
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
 
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).pptxKalashJain27
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonRaajendra M
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxjchandrasekhar3
 
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.pptxNishanSidhu2
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29Bilal Ahmed
 
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 FunctionsOluwaleke Fakorede
 
Ch 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptxCh 7 Dictionaries 1.pptx
Ch 7 Dictionaries 1.pptxKanchanaRSVVV
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonMSB Academy
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana Shaikh
 
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
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 

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
 
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#
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 

More from 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

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

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)