Python 3

home

Introduction to Python

davidbpython.com




Dictionaries: Rankings

dictionary rankings

Dictionaries can be sorted by value to produce a ranking.






loop through dict keys and values

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

                           # (etc.)

Note that plain 'for' looping over a dict delivers the keys:

for key in mydict:
    print(key)             # prints a, then b, then c...




review: sorting any container with sorted()

With any container or iterable (list, tuple, file), sorted() returns a list of sorted elements.


namelist = ['jo', 'pete', 'michael', 'zeb', 'avram']

slist = sorted(namelist)          # ['avram', 'jo', 'michael', 'pete', 'zeb']

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.





sorting a dict (sorting its keys)

sorted() returns a sorted list of a dict's keys.


bowling_scores = {'jeb': 123, 'zeb': 98, 'mike': 202, 'alice': 184}

sorted_keys = sorted(bowling_scores)

print(sorted_keys)     # [ 'alice', 'jeb', 'mike', 'zeb' ]

for key in sorted_keys:
    print(f'{key}={bowling_scores[key]}')




sorting a dictionary's keys by its values

A special "sort criteria" argument 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 specify an alternate criteria by which we might sort the keys. The .get() method takes a key and returns a value from the dict, which is what we are asking sorted() to do with each key when sorting by value. However, this complex sorting is more advanced a topic than we cabn cover here.





assign multiple values to individual variables

multi-target assignment performs the assignments in one statement


csv_line = "Haddad's,PA,239.50"

row = csv_line.split(',')        # ["Haddad's", 'PA', '239.50']

codata = ["Haddad's", 'PA', '239.50']

company, state, revenue = codata

print(company)       # "Haddad's"
print(revenue)       # 239.50

csv_line = 'jk43:23 Marfield Ln.:Plainview:NY:10024'

stuid, street, city, state, zip = csv_line.split(':')

print(stuid)      # 'jk43'
print(city)       # 'Plainview'




build up a dict from two fields in a file

As with all containers, we loop through a data source, select and add to a dict.


ids_names = {}                 # initialize an
                               # 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()




[pr]