so this data file is called friends2.txt:
John,555-234-9876,May 5
Mary,556-987-2367,December 12
Albert,555-987-6765,June 12
Leo,555-789-9865,February 25
Ruth,555-786-1238,October 2
Fred,556-235-4536,June 17
However, I must create the dictionary where the name (ie. John) is the key, and the values are a list of the phone number and birthday (ie. {'John': (555-234-9876, May 5)}. However, I am unsure of how to sort(by key value) and print out every line of the text file one after the other. the aimed output is:
Albert 555-987-6765 June 12
Fred 556-235-4536 June 17
John 555-234-9876 May 5
Leo 555-789-9865 February 25
Mary 556-987-2367 December 12
Ruth 555-786-1238 October 2
So far, my code:
if __name__ == '__main__':
file_name = "friends2.txt"
inf = open(file_name,"r")
myfriends = {}
# how to build ? myfriends = {key, list(myfriends[name][0], myfriends[name])}
for line in inf:
fields = line.split(",")
myfriends[fields[0]] = fields[1:]
# value is a list containing the phone number, in position 0, and the birthday in position 1
# build a list from the phone number and birthday for the "value" in the key-value pair
for name in sorted(myfriends):
print("{} {} {}".format(sorted(myfriends), myfriends[name][0], myfriends[name][1].strip("\n")))
I tried
for name in sorted(myfriends):
print("{} {} {}".format(sorted(myfriends), myfriends[name][0], myfriends[name][1].strip("\n")))
but this yields
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-987-6765 June 12
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 556-235-4536 June 17
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-234-9876 May 5
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-789-9865 February 25
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 556-987-2367 December 12
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-786-1238 October 2
How would i make it so the key (names) are sorted and iterated properly? Any help would be appreciated!