Python 3home |
Introduction to Python
davidbpython.com
Dictionaries can be sorted by value to produce a ranking.
We loop through keys and then use subscripting to get values.
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in mydict: # a
val = mydict[key]
print(key) # a
print(val) # 1
print()
# b
# 2
# (continues with 'c' and 'd')
Ex. 6.8
With any container or iterable (list, tuple, file), sorted() returns a list of sorted items.
namelist = ['banana', 'apple', 'dates', 'cherry']
slist = sorted(namelist, reverse=True)
print(slist) # ['dates', 'cherry', 'banana', 'apple']
Remember that no matter what container is passed to sorted(), the function returns a list. Also remember that the reverse=True argument to sorted() can be used to sort the items in reverse order.
sorted() returns a sorted list of a dict's keys.
bowling_scores = {'bob': 123, 'zeb': 98, 'mike': 202, 'alice': 184}
sorted_keys = sorted(bowling_scores)
print(sorted_keys) # [ 'alice', 'bob', 'mike', 'zeb' ]
Ex. 6.9
A special argument to sorted() can cause Python to sort a dict's keys by its values.
bowling_scores = {'jeb': 123, 'zeb': 98, 'mike': 202, 'alice': 184}
sorted_keys = sorted(bowling_scores, key=bowling_scores.get)
print(sorted_keys) # ['zeb', 'jeb', 'alice', 'mike']
for player in sorted_keys:
print(f"{player} scored {bowling_scores[player]}")
## zeb scored 98
## jeb scored 123
## alice scored 184
## mike scored 202
The key= argument allows us to instruct sorted() how to sort the keys. The sorting works in part by use of the dict .get() method (discussed later). Passing .get to sorted() causes it to sort by value instead of by key. Ex. 6.10
multi-target assignment allows us to "unpack" the values in a container.
If the container on the right has 3 values, we may unpack them to three named variables.
company, state, revenue = ["Haddad's", 'PA', '239.50']
print(company) # Haddad's
print(revenue) # 239.50
But if the values we want are in a CSV line we can split them to a list -- and then assign them using multi-target assignment.
csv_line = "Haddad's,PA,239.50"
company, state, revenue = csv_line.split(',')
print(company) # Haddad's
print(state) # PA
Ex. 6.14
As with all containers, we loop through a data source, select and add to a dict.
ids_names = {} # empty dict
fh = open('student_db.txt')
for line in fh:
stuid, street, city, state, zip = line.split(':')
ids_names[stuid] = state # key id is paired to
# student's state
print("here is the state for student 'jb29': ")
print(ids_names['jb29']) # NJ
fh.close()
ex. 6.15