我正在尝试从字典中提取某些值并以特定方式显示它。我将在下面向您展示我的代码示例:
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
答案 0 :(得分:3)
我使用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
答案 1 :(得分:1)
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'}]
print [(i["Titel"],i["Starttime"],i["Surname"], i["Email"]) for i in k]
您可以使用此功能,您将获得所需信息的tuple
。
答案 2 :(得分:1)
def print_my_d(d):
print(d[0]['Titel'], d[0]['Starttime'])
for l in d[:2]:
print(l['Surname'], l['Name'], l['Email'])
print()
print(d[2]['Titel'],d[2]['Starttime'])
print("{}, {}, {}".format(d[2]['Surname'],d[2]['Name'], d[2]['Email']))
print_my_d(d)
Rush 20:30
Cake Floris Floris@email.com
Pie Jaron JaronPie@email.com
Underneath 04:00
Klassie, Klaas, Klassieboy@gmail.com