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