-2

So I'm creating some objects with information from a CSV file like that:

def ajouter_morceaux_csv(db,csv):
    data_csv= read_data(csv)

    for i in range(len(data_csv[0])):
        titre = data_csv[0][i]
        année = data_csv[1][i]
        artistes = data_csv[2][i]
        style= data_csv[3][i]
        guitare = data_csv[4][i]
        note = data_csv[5][i]
        with shelve.open(db) as db_data:
            del(db_data[str(data_csv[0][i])])
            db_data[str(data_csv[0][i])]= Data_Song(titre,année,artistes,style,guitare,note=note)

Then I need to print out this "database". I need to print it sorted first alphabetically by title and then by value of "note"

I used the title as the key name so it could be easier but I still don't know how could I sort it by value note of the object.

This is how I print it:

def afficher_tout(db):
    with shelve.open(db) as db_data:
        klist = list(db_data.keys())
        klist.sort()
        print("Base de données musicales complète :")
        print()
        for key in klist:
            print("Titre: " + str(db_data[key].titre))
            print("Année: " + str(db_data[key].année))
            print("Artistes: " + str(db_data[key].artistes))
            print("Style: " + str(db_data[key].style))
            print("Guitare: " + str(db_data[key].guitare))
            print("note: " + str(db_data[key].note))
            print()

I can't import any module to this project beside shelve,os,sys

Felix Dumitrascu
  • 115
  • 1
  • 10

1 Answers1

1

You can provide a key function to .sort() and sorted().

klist = sorted(db_data.keys(), key=lambda k: (db_data[k].titre, db_data[k].note))
blueteeth
  • 3,330
  • 1
  • 13
  • 23