Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Reposted (sorry the indentions don\'t show up...): How would I modify this funct

ID: 3640246 • Letter: R

Question

Reposted (sorry the indentions don't show up...):

How would I modify this function:

def createCityPopDict():
file = open("pop3.txt","r")
D = {}
for line in file:
if line != '':
if line[:-1]:
line = line[:-1]
L = line.split()
key = L[0]
value = L[1]
D[key] = value
file.close()
return D

to follow this?

1. createCityPopDict() - return D. Write a function which opens and reads (and closes when finished) file pop3.txt and returns a dictionary of city : pop associated key:value pairs. For example,

'new york,ny' : 8391881
'los angeles,ca' : 3831868
'chicago,il' : 2851268

should be the first 3 key:value pairs entered into D.

This is the txt file:
pop3.txt - a text file with lines of rank, city name, population for all us cities having population greater than 100000 (276 cities total). Here is a sample of the first 20 lines of this file:

1 new york,ny 8391881
2 los angeles,ca 3831868
3 chicago,il 2851268
4 houston,tx 2257926
5 phoenix,az 1593659
6 philadelphia,pa 1547297
7 san antonio,tx 1373668
8 san diego,ca 1306300
9 dallas,tx 1299542
10 san jose,ca 964695
11 detroit,mi 910921
12 san francisco,ca 815358
13 jacksonville,fl 813518
14 indianapolis,in 807584
15 austin,tx 786386
16 columbus,oh 769332
17 fort worth,tx 727577
18 charlotte,nc 709441
19 memphis,tn 676640
20 boston,ma 645169

Any insight, steps, or hints are greatly appreciated!

Explanation / Answer

def createCityPopDict():
    file = open("pop3.txt","r")
    D={}
    for line in file:
        line=line.split()
        if len(line)==3:
            name=line[1]
            value=line[2]
            D[name]=value

    file.close()
    return D

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote