Home > Blockchain >  convert and format list of dictionaries in Pyton by values
convert and format list of dictionaries in Pyton by values

Time:11-28

Hope someone can help me with dictionary:

    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" ]
  }
]

As output, I need to see who bought economy and who bought business class: With sorting = ascending by class and inside class by firstname. So business comes first, then economy. and Alina comes first in both classes, because she bought both classes.

business: Alina Hoper, Bill Flow, ...
economy: Alina Hoper, David Brown, ...

I tried to write function, but can not understand right now where to start sorting and how to convert dictinory and group data by class:

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))

Hope someone can help

CodePudding user response:

You should first get the list of economy/business customers and then print the names from those lists:

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}")

Output:

business : Alina Hoper, Bill Flow
economy : Alina Hoper, David Brown, James Frank
Edit: if you don't know the class names beforehand you can create a set of classes:
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}")
  • Related