This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
forked from edooley7/dsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
advanced_python_dict.py
87 lines (64 loc) · 1.69 KB
/
advanced_python_dict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import re
### Question 6
print "\nQ6"
# Open CSV
f_in = open('faculty.csv', 'r')
# Skip first line
f_in.next()
faculty = dict()
for line in f_in:
# Split line into fields
line = [w.strip() for w in line.split(',')]
# Extract info
lastname = line[0].split()[-1]
degree = line[1]
title = re.match('.*Professor', line[2]).group()
email = line[3]
# Add data to dictionary
value = [degree, title, email]
if lastname in faculty:
faculty[lastname] += [value]
else:
faculty[lastname] = [value]
# Close file
f_in.close()
# Print first 3 entries
for k in faculty.keys()[:3]:
print "`%s: %s` "%(k,faculty[k])
### Question 7
print "\nQ7"
# Open CSV
f_in = open('faculty.csv', 'r')
# Skip first line
f_in.next()
faculty = dict()
for line in f_in:
# Split line into fields
line = [w.strip() for w in line.split(',')]
# Get first name and last name
ind = line[0].rfind(' ')
lastname = line[0][ind+1:]
firstname = line[0][:ind]
# Get degree
degree = line[1]
# degree = re.sub('Ph\.?D\.?', 'Ph.D.', degree, flags=re.IGNORECASE)
# degree = re.sub('Sc\.?D\.?', 'Sc.D.', degree, flags=re.IGNORECASE)
# Get title
title = re.match('.*Professor', line[2]).group()
email = line[3]
# Add entry to dictionary
key = (firstname, lastname)
value = [degree, title, email]
faculty[key] = value
# Close file
f_in.close()
# Print first 3 entries
for k in faculty.keys()[:3]:
print "`%s: %s` "%(k,faculty[k])
### Question 8
print "\nQ8"
# Sort keys by last name
keys_sorted = sorted(faculty.keys(), key=lambda k: k[1])
# Print all key/value pairs
for k in keys_sorted:
print "`%s: %s` "%(k,faculty[k])