Domanda Risolto Ho un problema con i dizionari.

Stato
Discussione chiusa ad ulteriori risposte.

Giuliopyt

Utente Iron
28 Marzo 2021
7
2
4
15
Questo è il secondo post che metto in questo forum. Ho messo un post dove ho scritto che ho iniziato da poco a fare un mooc e fino ad oggi non ho avuto nessun problema. Il problema l'ho con i dizionari.

Python:
#Recall in the previous problem you counted the number of
#instances of a certain first name in a list of full names.
#You returned a dictionary with the name as the key, and the
#number of times it appeared as the value.
#
#Modify that code such that instead of having a count as the
#value, you instead have a list of the full names that had
#that first name. So, each key in the dictionary would still
#be a first name, but the values would be lists of names.
#Make sure to sort the list of names, too.
#
#Name this new function name_lists.
def add_member_to_group(dictn, group_name, fullname):
    #print("dic",group_name, fullname)
    try:
      dictn[group_name].append(fullname)
    except KeyError:
      dictn[group_name] = [fullname]  

    #this_group = dictn[group_name]
    #this_group.append(fullname)


#Add your function here!
def name_lists(nlist):
    # lista dei nomi
    listname=[]
    # dizionario con nomi completi + nomi

    # dizionario return funzione con nome + lista
    dictname={}
    for name in nlist:
        #print("crealista",name)        
        fname=name.split()
        listname.append(fname[0])
        #print("fname0",fname[0],name)        
        
        
        add_member_to_group(dictname,fname[0],name)
        
        #if fname[0] in dictname:
        #   dictname[fname[0]].append(name)
        #else:
        #   dictname[fname[0]]=name
        
        #dictname[fname[0]]=name
        
        #dictname.append(fname)
        #print(fname," ",name)
        
    #for name in listname:
        #fname=name.split()
        #listname.append(fname[0])
        
        #print("creadic",name)
        #if name in dictname:
         # dictname[name]+=1
          
        #else:
         # dictname[name]=1  
    #print(dictname)
    return dictname
        
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print (although the order of the keys may vary):
#{'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Fry', 'Shelba Odle'],
#'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyner', 'Brenton Zuber'],
#'Maren': ['Maren Fry'], 'Nicol': ['Nicol Barthel']}

name_list = ["David Joyner", "David Zuber", "Brenton Joyner",
             "Brenton Zuber", "Nicol Barthel", "Shelba Barthel",
             "Shelba Crowley", "Shelba Fernald", "Shelba Odle",
             "Shelba Fry", "Maren Fry"]
print(name_lists(name_list))

Ricevo questo errore:
[Executed at: Fri Apr 2 14:51:57 PDT 2021]
We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left:
We tested your code with names = ["David Joyner", "David Zuber", "Brenton Joyner", "Brenton Zuber", "Nicol Barthel", "Shelba Barthel", "Shelba Crowley", "Shelba Fernald", "Shelba Odle", "Shelba Fry", "Maren Fry"].
We expected name_lists to return the dict
{'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyner', 'Brenton Zuber'], 'Nicol': ['Nicol Barthel'], 'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Fry', 'Shelba Odle'], 'Maren': ['Maren Fry']}.
However, it returned the dict
{'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyner', 'Brenton Zuber'], 'Nicol': ['Nicol Barthel'], 'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Odle', 'Shelba Fry'], 'Maren': ['Maren Fry']}.
 
Da quello che riporta l'errore sembra solo che tu debba ordinare i nomi-cognomi, perche' l'unica differenza ( a meno che non mi sfugga altro) sembra essere l'ordine Shelba Odle - Shelba Fry
Corretto? E' questo il tuo dubbio?
 
Da quello che riporta l'errore sembra solo che tu debba ordinare i nomi-cognomi, perche' l'unica differenza ( a meno che non mi sfugga altro) sembra essere l'ordine Shelba Odle - Shelba Fry
Corretto? E' questo il tuo dubbio?
Allora, non è che sia una cosa importante. Non penso valga la pena di insistere su questo esercizio, ma è meglio che vada avanti con gli altri.
Quindi penso di lasciarlo così come è, cioè errato secondo loro.
Ma giusto per curiosità, come potrei ordinare le liste presenti nei valori del dizionario? Io ho provato a scrivere questo comando:

dictname.items().sort()

ma ho ricevuto questo:
AttributeError: 'dict_items' object has no attribute 'sort'
Command exited with non-zero status 1

Perchè ho questo errore?
 
Tu non puoi ordinare un dict, infatti nell'errore ti dice "'dict_items' object has no attribute 'sort'". ovvero: i dict non hanno la funzione sort
Tu dovrei ordinare l'array che coincide con il valore del dict per ogni chiave, quindi: per ogni elemento del dict (coppia key-value), riordino value
Se non mi sono spiegato bene dimmelo e ti scrivo il codice
 
Ok. Mi ha funzionato!. Perfetto. Sinceramente Non ho ben capito ancora se il tuo suggerimento è stato determinante (ma probabilmente si) oppure se dopo vari tentativi andati a vuoto sono riuscito a farne uno funzionante. Comunque grazie.
Ho scritto questo codice:

sorted(dictname.items())
for keys in dictname:
for nomi in dictname.values():
nomi.sort()

ed ho ottenuto l'ok seguente:

[Executed at: Sat Apr 3 3:36:42 PDT 2021]
Well done! You can see the full results of your submission by selecting full_results.txt from the dropdown in the top left. You should see your score updated on your Progress page as well. You might also find some sample_answer files in the drop down with other answers to this problem. If they are available, we recommend reading them to see some optimal approaches!

Fra non molto passerò al livello 4 (che, presumo, sia molto più difficile dei precedenti), se per caso ci saranno altri esercizi che mi bloccano proverò ad aprire un'altra discussione.
Grazie, saluti.

A proposito, come faccio a mettere risolto in questo post? Non vedo nessun menu particolare. Ci pensate voi? Grazie.
 
Stato
Discussione chiusa ad ulteriori risposte.