convert and format list of dictionaries in Pyton by values

  dictionary, format, function, list, python-3.x

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):
    # of course, we should always check the arguments and whether keys and values are present
    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

Source: Python-3x Questions

LEAVE A COMMENT