在 Python 中按值转换和格式化字典列表
Posted
技术标签:
【中文标题】在 Python 中按值转换和格式化字典列表【英文标题】:convert and format list of dictionaries in Pyton by values 【发布时间】:2022-01-04 02:25:58 【问题描述】:希望有人能帮我查字典:
data = [
"firstname" : "David",
"lastname" : "Brown",
"class" : [ "economy" ]
,
"firstname" : "Alina",
"lastname" : "Hoper",
"class" : [ "economy", "business" ]
,
"firstname" : "Bill",
"lastname" : "Flow",
"class" : [ "business" ]
,
"firstname" : "James",
"lastname" : "Frank",
"class" : [ "economy" ]
]
作为输出,我需要看看谁买了经济舱,谁买了商务舱: 排序=按类升序,在类内部按名字升序。所以先做生意,再做经济。而阿丽娜在这两门课上都名列前茅,因为她买了这两门课。
business: Alina Hoper, Bill Flow, ...
economy: Alina Hoper, David Brown, ...
我尝试编写函数,但现在不明白从哪里开始排序以及如何按类转换字典和分组数据:
def analyze(customers_data):
data = ""
data += " \n".format(customers_data["firstname"], customers_data["lastname"])
data += " \n".format(customers_data["aff"])
return data
for d in orders:
print(analyze(d))
希望有人能帮忙
【问题讨论】:
【参考方案1】:您应该首先获取经济/商业客户的列表,然后打印这些列表中的名称:
data = [
"firstname" : "David",
"lastname" : "Brown",
"class" : [ "economy" ]
,
"firstname" : "Alina",
"lastname" : "Hoper",
"class" : [ "economy", "business" ]
,
"firstname" : "Bill",
"lastname" : "Flow",
"class" : [ "business" ]
,
"firstname" : "James",
"lastname" : "Frank",
"class" : [ "economy" ]
]
business_custom = [dic for dic in data if "business" in dic["class"]]
eco_custom = [dic for dic in data if "economy" in dic["class"]]
business_names = ', '.join(sorted([f"dic['firstname'] dic['lastname']" for dic in business_custom]))
economy_names = ', '.join(sorted([f"dic['firstname'] dic['lastname']" for dic in eco_custom]))
print(f"business: business_names")
print(f"economy: economy_names")
输出:
business : Alina Hoper, Bill Flow
economy : Alina Hoper, David Brown, James Frank
编辑:如果你事先不知道类名,你可以创建一组类:
class_set = set()
for dic in data:
for c in dic['class']:
class_set.add(c)
for c in sorted(list(class_set)):
custom = [dic for dic in data if c in dic["class"]]
names = ', '.join(sorted([f"dic['firstname'] dic['lastname']" for dic in custom]))
print(f"c: names")
【讨论】:
非常感谢。它有助于。我还尝试打开按 lastanme 排序,它有效,但认为它不正确:names = ', '.join(sorted([f"dic['firstname'] dic['lastname']" for dic in custom], key=lambda x: x[6])) >>> 它显示了我想要的方式,但如果我做对了,它会按第 6 个值(字母)排序。可能你有一个提示如何输入单词而不是字母。我试过 ['lastname'] 但它显示:字符串索引必须是整数 您可以通过定义custom = [dic for dic in sorted(data, key=lambda x:x['lastname']) if c in dic["class"]]
直接按姓氏对客户进行排序(删除names
中的排序以避免列表随后按名字排序)以上是关于在 Python 中按值转换和格式化字典列表的主要内容,如果未能解决你的问题,请参考以下文章