Skip to main content
 首页 » 编程设计

Python之以特定方式从字典中提取信息

2025年05月04日33grandyang

我正在尝试从字典中提取某些值并以特定方式显示它。我将在下面向您展示我的代码示例:

dict = [{'Titel': 'Rush', 'Name': 'Floris', 'Starttime': '20:30', 'Email': 'Floris@email.com', 'Supplier': 'RTL8', 'Surname': 'Cake', 'Code': 'ABC123'}, 
 {'Titel': 'Rush', 'Voornaam': 'Jaron', 'Starttime': '20:30', 'Email': 'JaronPie@email.com', 'Supplier': 'RTL8', 'Surname': 'Pie', 'Code': 'XYZ123'}, 
 {'Titel': 'Underneath', 'Name': 'Klaas', 'Starttime': '04:00', 'Email': 'Klassieboy@gmail.com', 'Supplier': 'RTL8', 'Surname': 'Klassie', 'Code': 'fbhwuq8674'}] 

那是我的字典。我想要的输出是:

Titel, Starttime, 
Surname, Name, Email 

所以它看起来像这样:

Rush, 20:30,  
Cake, Floris, Floris@email.com 
Pie, Jaron, JaronPie@email.com 
 
Underneath, 04:00, 
Klassie, Klaas, Klassieboy@gmail.com 

请您参考如下方法:

感谢 VKS,我使用了 VKS 的代码来构建它:P

使用 groupy , list comprehension和 sting formatting

代码:

from itertools import groupby 
k = [{'Titel': 'Rush', 'Name': 'Floris', 'Starttime': '20:30', 'Email':      'Floris@email.com', 'Supplier': 'RTL8', 'Surname': 'Cake', 'Code': 'ABC123'}, 
{'Titel': 'Rush', 'Voornaam': 'Jaron', 'Starttime': '20:30', 'Email': 'JaronPie@email.com', 'Supplier': 'RTL8', 'Surname': 'Pie', 'Code': 'XYZ123'}, 
{'Titel': 'Underneath', 'Name': 'Klaas', 'Starttime': '04:00', 'Email': 'Klassieboy@gmail.com', 'Supplier': 'RTL8', 'Surname': 'Klassie', 'Code': 'fbhwuq8674'}] 
 
lst=[(i["Titel"],i["Starttime"],i["Surname"],i.get("Name","None"), i["Email"]) for i in k] 
lst.sort(key=lambda x:(x[0],x[1])) 
for key,groups in groupby(lst,key=lambda x:(x[0],x[1])): 
    print "{}\t{}".format(key[0],key[1]) 
    for value in groups: 
        print "{}\t{}\t{}".format(value[2],value[3],value[4]) 
    print "" 

输出:

Rush    20:30 
Cake    Floris  Floris@email.com 
Pie     None    JaronPie@email.com 
 
Underneath      04:00 
Klassie Klaas   Klassieboy@gmail.com