简体   繁体   English

将字典转换为元组排序列表

[英]Converting Dictionary to Sorted List of Tuples

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.然后我尝试将键和所有值分开,并用 for 语句将它们重新缝合在一起,但我已经花了足够的时间在这上面,因为我只是被阻塞了,不明白为什么它不会通过通过。

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.对于功能#1,测试失败。
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.对于功能#2,测试失败。
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

@Akaisteph7 thank you that answer worked. @Akaisteph7 谢谢你的回答有效。 I sorted it by sorta.sort() and then everything passed through correctly.我通过 sorta.sort() 对它进行排序,然后一切都正确通过了。

here is the final code:这是最终的代码:

def sort_contacts(diction):
    sorta = [(k, v[0], v[1]) for k,v in diction.items()]
    sorta.sort() 
    return sorta

Thanks everybody!谢谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM