How to write an alphabetical list of names using the Python OrderedDict?

1
Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = {"Nome": Nomes,"Telefone":Telefones,"Endereço":Endereços,
          "Email": Emails}
entrada = ""

print("Bem-vindo a nossa Agenda!!!!!")
while entrada != "s":

    nome = input("Digite o nome: ")
    Nomes.append(nome)
    telefone = input("Digite o telefone: ")
    Telefones.append(telefone)
    endereço = input("Digite o endereço: ")
    Endereços.append(endereço)
    email = input("Digite o email: ")
    Emails.append(email)
    #print(Agenda)
    entrada = input("Deseja sair? ")
    print()
    if entrada.lower() == "s":
        ordenada = sorted(Agenda['Nome']) 
        for nome in ordenada:  
            print()
            print("Nome: ",Agenda['Nome'][Nomes.index(nome)])
            print("Telefone: ",Agenda['Telefone'][Nomes.index(nome)])
            print("Endereço: ",Agenda['Endereço'][Nomes.index(nome)])
            print("Email: ",Agenda['Email'][Nomes.index(nome)])
            print()
        break

The above program creates an Agenda and prints a, in alphabetical order of the Names. Is it possible to do the same program using Python's OrderedDict?

Draft:

from collections import OrderedDict

Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = OrderedDict()
Agenda['Nome'] = Nomes
    
asked by anonymous 07.04.2018 / 00:43

1 answer

3

You apparently read some data as long as the user wants and then displays them all in alphabetical order based on the name. It will be easier for you to create a dictionary for each record and maintain a list of dictionaries. Something like this:

from operator import itemgetter

agenda = []
print('Seja bem-vindo')
while True:
    nome = input('Nome: ')
    telefone = input('Telefone: ')
    email = input('E-mail: ')
    agenda.append(dict(nome=nome, telefone=telefone, email=email))
    entrada = input('Deseja sair? ')
    if entrada.lower() == 's':
        for pessoa in sorted(agenda, key=itemgetter('nome')):
            print('{p[nome]}, {p[telefone]}, {p[email]}'.format(p=pessoa))
        break

See working at Repl.it

This also facilitates other operations with the list, such as searching all the records of people with the name beginning with the letter A:

nomes_com_A = (pessoa for pessoa in agenda if pessoa['nome'].startswith('A'))

for pessoa in nomes_com_A:
    print('{p[nome]}, {p[telefone]}, {p[email]}'.format(p=pessoa))
    
07.04.2018 / 01:31