简体   繁体   English

如何在Python中按字典的姓氏对字典列表进行排序?

[英]How do I sort a list of dictionaries by last name of the dictionary in Python?

I need to write a sort_contacts function that takes a dictionary of contacts as a parameter and returns a sorted list of those contacts, where each contact is a tuple. 我需要编写一个sort_contacts函数,该函数将联系人字典作为参数,并返回这些联系人的排序列表,其中每个联系人都是一个元组。

The contacts dictionary that will be passed into the function has the contact name as its key, and the value is a tuple containing the phone number and email for the contact. 将传递到函数中的联系人字典以联系人名称作为键,值是一个包含该联系人的电话号码和电子邮件的元组。

contacts = {name: (phone, email), name: (phone, email), etc.} 联系人= {姓名:(电话,电子邮件),姓名:(电话,电子邮件)等}

The sort_contacts function should then create a new, sorted (by last name) list of tuples representing all of the contact info (one tuple for each contact) that was in the dictionary. 然后,sort_contacts函数应创建一个新的,已排序(按姓氏排序)的元组列表,该列表表示字典中的所有联系人信息(每个联系人一个元组)。 It should then return this list to the calling function. 然后,应将此列表返回给调用函数。

For example, given a dictionary argument of: 例如,给定一个字典参数:

    {("Horney, Karen": ("1-541-656-3010", "karen@psychoanalysis.com"),
    "Welles, Orson": ("1-312-720-8888", "orson@notlive.com"),
    "Freud, Anna": ("1-541-754-3010", "anna@psychoanalysis.com")}

sort_contacts should return this: sort_contacts应该返回以下内容:

    [('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')]**

You can simply add the key and value and sort : 您可以简单地添加keyvalue并进行sort

>>> sorted((k,)+v for k, v in contacts.items())
[('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')]

If you don't care about a nested tuple then you can simply: 如果您不关心嵌套元组,则可以简单地:

>>> sorted(contacts.items())
[('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'))]
def sort_contacts(contacts):
    real_contacts=[]
    function_keys=contacts.keys()

    for key in sorted(function_keys):
        data = (key, contacts[key][0], contacts[key][1])
        real_contacts.append(data)

    return real_contacts

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

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