How to write a calendar in alphabetical order of Names using Python Ordereddict?

Asked

Viewed 479 times

0

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 the, in alphabetical order of the Names. You can do the same program using Python Ordereddict?

Draft:

from collections import OrderedDict

Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = OrderedDict()
Agenda['Nome'] = Nomes
  • 1

    Why separate all values in different lists? Wouldn’t it be better to create an object for each record and create a list of objects?

  • @Anderson Carlos Woss: I’m quite limited in programming. I only managed to do so! Ordereddict would help in something?

1 answer

3

Apparently, you read some data as long as the user wishes and then display 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 on Repl.it

This even facilitates other operations with the list, such as searching all records of people who have the name starting 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))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.