So I am trying to convert a dictionary into a sorted list containing tuples. I have been able to convert the dictionary to a sorted list no problem. My issue is creating a tuple out of the key AND corresponding values, then passing that into a sorted list.
I have tried just turning the dictionary into a sorted list (which technically works but the tuple seems to be a separate entity in the list).
Then I tried to pull the key and the all the values apart and stitch them back together with a for statement but I've spent enough time on this now that I'm just blocked up and can't see why it won't pass through.
Below are the two functions I have tried to create:
#function #1
def sort_contacts(diction):
my_key_list = list(diction.keys())
my_val_list = list(diction.values())
for x in range(0,len(my_key_list)):
for k in my_key_list:
for x,v in my_val_list:
new_val=(k, x, v)
new_list=[new_val]
return(new_list)
#function #2
def sort_contacts(diction):
sorta = [(k,v) for k,v in diction.items()]
sorta = list(sorta)
sorta.sorta
#sortc = sortb.split()
return sorta
For function #1, Test Failed.
Expected:
[('Freud, Anna', '1-541-754-3010', 'anna@psychoanalysis.com'), ('Horney, Karen', '1-541-656-3010', 'karen@psychoanalysis.com'), ('Welles, Orson', '1-312-720-8888', 'orson@notlive.com')]
but got:
[('Freud, Anna', '1-541-754-3010', 'anna@psychoanalysis.com')]
For function #2, Test Failed.
Expected:
[('Freud, Anna', '1-541-754-3010', 'anna@psychoanalysis.com'), ('Horney, Karen', '1-541-656-3010', 'karen@psychoanalysis.com'), ('Welles, Orson', '1-312-720-8888', 'orson@notlive.com')]
but got:
[('Freud, Anna', ('1-541-754-3010', 'anna@psychoanalysis.com')), ('Horney, Karen', ('1-541-656-3010', 'karen@psychoanalysis.com')), ('Welles, Orson', ('1-312-720-8888', 'orson@notlive.com'))]
I think what you are looking for is something like:
def sort_contacts(diction):
sorta = [(k, v[0], v[1]) for k,v in diction.items()]
# sort it somehow?
return sorta