Rhonal Velasco
Fredy Mendoza Vargas
Muchas gracias
Omar Daniel Centeno
Buena
Refactoriza tu CRUD de clientes en Python y pasa de una lista con nombres a diccionarios con estructura clara: name, company, email y position. Con una sola función para capturar campos, mejorarás la entrada de datos y el formateo al listar por UID. Además, verás por qué refactorizar es parte natural del trabajo en software.
¿Cómo transformar la lista de clientes con diccionarios en Python?
Usar diccionarios permite definir explícitamente qué es un cliente. En lugar de una lista de strings, se modela cada cliente con llaves y valores. Así, el código se vuelve más expresivo y fácil de mantener.
¿Qué estructura tiene cada cliente?
clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position': 'software engineer', }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position': 'Data Engineer', }, ]
¿Por qué usar diccionarios y no solo nombres?
¿Cómo adaptar create y la captura de datos con get_client_field?
Antes, create recibía solo el nombre. Ahora, recibe el diccionario completo del cliente. Para capturar datos, se usa una función genérica que pide cada campo y no permite continuar con valores vacíos.
¿Cómo se captura cada campo con una función genérica?
def get_client_field(field_name): field = None while not field: field = input(f'What is the client {field_name}? ') return field
¿Cómo se envía el objeto cliente a create?
client = { 'name': get_client_field('name'), 'company': get_client_field('company'), 'email': get_client_field('email'), 'position': get_client_field('position'), } clients.append(client)
¿Qué pasa si el usuario no ingresa datos?
¿Cómo listar clientes con formato y acceder por índice (UID)?
El listado ahora muestra un UID (el índice en la lista) y los campos clave del cliente. Así el resultado es legible y útil para futuras operaciones.
¿Cómo imprimir UID, name, company, email y position?
for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid=idx, name=client['name'], company=client['company'], email=client['email'], position=client['position'], ))
¿Qué se recomienda para update, delete y search?
¿Cómo se probó la creación de un cliente?
python main.py.¿Te animas a completar update, delete y search usando el UID y funciones auxiliares? Comparte tus dudas o tu solución en los comentarios.
Rhonal Velasco
Fredy Mendoza Vargas
Muchas gracias
Omar Daniel Centeno
Buena
import sys clientes = [ { 'name': 'Juan', 'company': 'Maxidespensa', 'email' : 'Juan@maxi.com', 'position' : 'Sofware Engineer' }, { 'name': 'Pedro', 'company': 'Google', 'email' : 'Pedro@google.com', 'position' : 'UX Designer' }, ] def create_client(client_name): global clientes if client_name not in clientes: clientes.append(client_name) else: print('Client alredy is in client\'s list') def list_clients(): for idx, cliente in enumerate(clientes): print('{uid} | {name} | {company} | {email} | {position}'.format( uid=idx, name=cliente['name'], company=cliente['company'], email=cliente['email'], position=cliente['position'] )) def update_client_search(client_name): global clientes indice = 0 for idx in clientes: indice += 1 for values in idx.values(): if client_name == values: return indice - 1 def update_client(client_name, update_people): global clientes indice = int(update_client_search(client_name)) clientes [indice] = update_people def searh_client(name): global clientes for idx in clientes: for persona in idx.values(): if name == persona: return True else: False def delete_client(client_name): global clientes if client_name in clientes: clientes.remove(client_name) else: print('Not Found Client') def _print_welcome(): print('Welcome To Platzi Ventas') print('*' * 50) print('What would yo like to day') print('[L]ist clients') print('[C]reate client') print('[U]pdate client') print('[D]elete client') print('[S]earch client') def _get_client_field(field_name): field = None while not field: field = input('What is the client {}?'.format(field_name)) return field def _get_client_name(): client_name = None while not client_name: client_name = input('What is the client name? ') if client_name == 'exit': client_name = None break if not client_name: sys.exit() return client_name if __name__ == "__main__": _print_welcome() commad = input() commad = commad.upper() if commad == 'C': client_name = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } create_client(client_name) list_clients() elif commad == 'D': client_name = _get_client_name() delete_client(client_name) list_clients() elif commad == 'U': client_name = _get_client_name() found = searh_client(client_name) if found: update_client_name = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } update_client(client_name,update_client_name) list_clients() else: print('The client: {} is not in our client\'s list'.format(client_name)) elif commad == "S": client_name = _get_client_name() found = searh_client(client_name) if found: print("The client is in the list client\'s") else: print('The client: {} is not in our client\'s list'.format(client_name)) elif commad == 'L': list_clients() else: print('Command Invalid')```
La funcion
def search_client(name):
era lo que me faltaba, no lograba llamar los valores de esta lista anidada dentro del for. Casi me explota la cabeza al ver que los podias llamar con
for persona in idx.values():
y poder compararlos con el nombre que dimos de input. ¿POR QUE PODEMOS LLAMAR A LOS VALORES DE "clients" MEDIANTE "idx"? es acaso por que "clients" es una lista anidada que contiene a los diccionarios con indices 0 y 1? entonces significa que:
0 = dict(“name”,“company”…)
y lo mismo para
1 =dict("name","company"...).
y llamando los por el indice de la lista anidada (que seria como su nombre) podemos usar el metodo .value(). Estoy en lo correcto?
Alvaro Eduardo Garzón Pira
¡Hola! El código de esta clase me generó varios conflictos porque estoy usando otras anotaciones y tengo algunas cositas añaditas mías, tuve más de 10 errores distintos al final de la clase, me llegó el pensamiento de ¿Y si esto no es para mí? Pero escuché la voz de Freddy diciendo "Lo que hacemos es dividir un gran problemas en problemas más pequeños", luego de esa frase, logré encontrar rápidamente cada uno de los errores, así que si tú, estás cuestionando si deberías de seguir o no, quiero decirte que sí, sí puedes lograr lo que quieres, puedes cambiar ese empleo mal pago y que no te gusta, puedes crear ese emprendimiento en tecnología y puedes todavía mucho más, recuerda, un gran problema lo divides en pequeños problemas, yo creo en ti desconocid@.
Jesús Enrique Morocoima Marcano
bueno ahora voy a intentar algo similar, ya que justo le agregado muchas cosas a mi código y en cada clase me toca adaptarlo lo bueno de esto es que estoy aprendiendo mas
Alejandro Romero
Wilson Alexander Caal Pacay
No se porque recorres el array jajaja, si la verdad estas pidiendo el numero de indice no es mejor solo eliminar de una vez ese numero
def delete_client(client_id): global clients client_id = int(client_id) # conviertes el string a un INT print(type(client_id)) del clients[client_id]
Omar Daniel Centeno
Bastante interesante lo del Dummy, muchas gracias
alvamar zapata
En el codigo que da el profesor, se busca el numero del cliente y no el nombre, es porque no puedo comparar con los elementos que estan adentro de la lista?
Marcelo Sánchez
Si es posible hacerlo, lo que pasa que al buscar el número de cliente, nos estamos "asegurando" que el elemento que estamos buscando sea único. Por ejemplo si ingresas a dos usuarios con el nombre "Carlos" (donde los otros datos son distintos), al buscar con un id tendremos un solo resultado, no así si buscamos por nombre (que también es valido)
David Vargas Domínguez
David Vargas Domínguez
Omar Daniel Centeno
Genial, muchas gracias
Aarón Espasandín
¿Queréis que todos los valores de cada cliente empiecen por mayúscula?:
# Capitalize all the values of every client for i in range(len(clients)): clients[i] = {k: v.capitalize() for k,v in clients[i].items()}
Incluirlo al inicio de list_clients() (después de global clients)
Omar Daniel Centeno
Genial. ¿Aquí estás aplicando list comprehensions?
Tarea
import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position': 'Sofware Engineer', }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position': 'Data Engineer', }, ] def create_client(client): if client not in clients: clients.append(client) else: print('Client already is in the client\'s list') def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}' .format(uid=idx, name=client['name'], company=client['company'], email=client['email'], position=client['position'])) def update_client(client_name): client = search_client(client_name) if client: print('****Udate to client*****') index = clients.index(client) clients[index] = _get_client_info() else: _no_clients_list() def delete_client(client_name): client = search_client(client_name) if client: clients.remove(client) else: _no_clients_list() def search_client(client_name): for client in clients: if client['name'].capitalize() != client_name.capitalize(): continue else: return client return {} def _print_welcome(): print('WELCOME TO PLATZI VENTAS') print('*' * 50)#imprimir 50 beces el asterisco print('What would you like to do doday?') print('[C]reate client') print('[U]pdate client') print('[D]elete client') print('[S]earch client') def _get_client_field(field_name): field = None while not field: field = input('What is the client {}?'.format(field_name)) return field def _get_client_name(): client_name = None while not client_name: client_name = input('What is the client name? ') if client_name == 'exit': client_name = None break if not client_name: sys.exit() return client_name def _get_client_info(): return { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position') } def _no_clients_list(): return print('Client is not in client\'s list') if __name__ == '__main__': _print_welcome() command = input() command = command.upper() if command == 'C': client = _get_client_info() create_client(client) list_clients() elif command == 'D': client_name = _get_client_field("name") delete_client(client_name) list_clients() pass elif command == 'U': client_name = _get_client_field("name") update_client(client_name) list_clients() pass elif command == 'S': client_name = _get_client_field("name") client = search_client(client_name) if client: print('The client: {} is in the client\'s list'.format(client_name)) else: print('The client: {} is not in our client\'s list'.format(client_name)) list_clients() pass else: print('Invalid command')
Gonzalo Ceron Denetro
Alexander Román
Si quiero quitar por codigo de cliente como haria ?
Cesar Hernández Ramírez
Yo lo hice así:
def delete_client(client_name): global clients found = None idx = 0 for i in clients: if i['name'].lower() == client_name: print(f'The client: {client_name.capitalize()} has been removed of the index: {idx}') clients.remove(i) found = True break if idx == len(clients) - 1: print(f'The client: {client_name.capitalize()} is not in my database') idx += 1
Sergio Andrés Pachón Dotor
La asignación de "[]" en el diccionario "clients" no significaría que ahora es una lista?
Andrés Felipe Rubiano Moreno
Si y no, la variable clients es una lista, pero la variable client es un diccionario. Por lo tanto clients es una lista de diccionarios.
Sergio Andrés Pachón Dotor
@andrésrubiano me es un tanto confuso con respecto a client, ya que no es explicito sino una construcción a lo largo del código, por lo cual operarlo is like "mmm ok"
rusbel bermúdez rivera
Mateo Echavarria
Marco Fernando Aguirre Noboa
Buena la idea de confirmacion para eliminar
Heberto Nicolás Hernández Andrade
David Esteban Solorzano Taborda
Santiago Ruiz Rincón
Gracias por tu aporte del delete ❤
Omar Daniel Centeno
Gracias
Osvaldo Trejo
Miguel Angel Ramos Palacios
Fabricio Galindo Copado
Pablo Perez
Alejandro Guerrero
Mi versión del código
import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position': 'Sofware Engineer', }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position': 'Data Engineer', }, ] def create_client(client): global clients if client not in clients: clients.append(client) else: print('Client already is in client\'s list') def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid = idx, name = client['name'], company = client['company'], email = client['email'], position = client['position'])) def ingress_client_data(): client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position') } return client def update_client(client_id, updated_client): global clients if len(clients) -1 >= client_id: clients[client_id] = updated_client else: print('Client is not in clients list') def delete_client(client_name): global clients if client_name in clients: clients.remove(client_name) else: print('Client is not in clients list') def search_client(client_name): for client in clients: if client != client_name: continue else: return True def _print_welcome(): print('WELCOME TO PLATZI VENTAS') print('*' * 50) print('What would yo like to do today?') print('[C]reated client') print('[U]pdate client') print('[L]ist clients') print('[D]elete client') print('[S]earch client') def _get_client_field(field_name): field = None while not field: field = input('What is the client {}? '.format(field_name)) return field if __name__ == '__main__': _print_welcome() command = input() command = command.upper() if command == 'C': client = ingress_client_data() create_client(client) list_clients() elif command == 'D': client_name = _get_client_name() delete_client(client_name) list_clients() elif command == 'U': list_clients() client_id = int(_get_client_field('id')) updated_client = ingress_client_data() update_client(client_id, updated_client) list_clients() elif command == 'L': list_clients() elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found: print('The client is in the client\'s list') else : print('The client: {} is not in client\'s list'.format(client_name)) else: print('Invalid command')
Hay un detalle interesante en la función delete_client(client_id), esto es al tener activado el pylint, ya que me marca que la variable client (dentro del for) no se usa en ningún momento. La corrección, después de haber leído cómo resolverlo es la siguiente:
Esta es la versión con el error de pylint W0612:
def delete_client(client_id): global clients for idx, client in enumerate(clients): # pylint retorna un error W0612 Unnused variable if idx == client_id: del clients[idx] break
Esta es la versión corregida:
def delete_client(client_id): global clients for idx, dummy_client in enumerate(clients): if idx == client_id: del clients[idx] break
Según lo leído aquí, es necesario que a las variables que (por alguna razón) no se van a usar, se les anteceda con dummy (o _, aunque esta opción es la menos recomendada por las confusiones que pueda ocasionar por los identificadores semi-privados) en el nombre, y de este modo Python la reconoce como una variable que puede no utilizarse.
Saludos 👋
Reto cumplido
Funciones Auxiliares
def _get_index(client_name): global clients for idx, client in enumerate(clients): print(idx) if client['name'] == client_name: return idx
Funciones Principales
def update_client(updated_client_fields, index): global clients if index is not None: clients[index].update(updated_client_fields) else: _message_to(client_name, False)
Llamados
if __name__ == '__main__': _print_welcome() command = input().upper() if command == 'C': client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'job': _get_client_field('job'), } create_client(client) list_clients() elif command == 'L': list_clients() elif command == 'U': client_name = input('Who do you want to update?: ') updated_client_fields = _set_update_fields() index = _get_index(client_name) update_client(updated_client_fields, index) list_clients() elif command == 'D': client_name = _get_client_name() index = _get_index(client_name) delete_client(client_name, index) list_clients() elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found: _message_to(client_name, True) else: _message_to(client_name, False) else: print('Invalid command')
Me falto una función auxiliar XD
def _set_update_fields(): updates = False updated_client_fields = {} while not updates: field = input('What field do you want to update?: ').lower() if field == 'exit': updates = True continue field_value = input('What is the new {}?: '.format(field)).capitalize() updated_client_fields.setdefault(field, field_value) return updated_client_fields
No se si sea la mejor solución, pero a esta llegue.
#El proyecto que se va a realizar, es un CRUD. #Tiene una área de lógica, área de persistencia y un área en la cuál interactuamos con el usuario, #esto lo haremos por medio de la línea de comandos. def _get_client_field(field_name): field = None while not field: field = input(f'What is the client {field_name}? ').capitalize() return field def update_client(arr): client_to_change = input("Which is the name of the client you would like to change? ").capitalize() for client in arr: if client_to_change == client['name']: client_index = arr.index(client) #Obtenemos el índice donde esta nuestro diccionario arr.pop(client_index) #Eliminamos el diccionario del array new_client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } arr.insert(client_index, new_client) #Agregamos el cliente actualizado en la posición anterior else: print("The client is not in the list") #if client_to_change in arr: # client_index = arr.index(client_to_change) # arr.pop(client_index) # client_updated = "" #while client_updated == "" or client_updated == " ": # client_updated = input("What is the new name of the client? ").capitalize() #arr.insert(client_index, client_updated) #print(arr) #print() #else: # print("The client is not in the list") def creat_cliente(arr): client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } if client not in arr: arr.append(client) else: print("The client is already in the list") def list_clients(arr): for idx, client in enumerate(arr): print(f'{idx}: {client["name"]}, {client["company"]}, {client["email"]}, {client["position"]}') def delete_client(arr): client_name = input("What is the client name of the cliente you want to delete? ").capitalize() for client in arr: if client_name == client['name']: arr.remove(client) print() else: print("The client is not in the list") def welcome_message(): print("WELCOME TO PLATZI VENTAS") print("*"*50) print("Press [S] to start.") def menu(): print("What would you like to do today?") print("[C]reate Client") print("[R]ead list of Clients") print("[U]pdate Client") print("[D]elete Client") print("[E]xit") def run(): clients = [ { 'name': "Pablo", 'company': "Google", 'email': "pablo@google.com", 'position': "Software Engineer" }, { 'name': 'Juan', 'company': 'Maxidespensa', 'email' : 'Juan@maxi.com', 'position' : 'Sofware Engineer' } ] menu_activo = 0 welcome_message() user_cmd = input().capitalize() if user_cmd == "S": menu_activo = 1 while menu_activo: menu() user = input().capitalize() if user == "C": creat_cliente(clients) elif user == "R": list_clients(clients) elif user == "U": update_client(clients) elif user == "D": delete_client(clients) elif user == "E": menu_activo = 0 else: menu_activo = 0 if __name__ == '__main__': run() ```#El proyecto que se va a realizar, es un CRUD. #Tiene una área de lógica, área de persistencia y un área en la cuál interactuamos con el usuario, #esto lo haremos por medio de la línea de comandos. *def* \_get\_client\_field(*field\_name*): field = None while not field: field = input(f'What is the client {*field\_name*}? ').capitalize() return field *def* update\_client(*arr*): client\_to\_change = input("Which is the name of the client you would like to change? ").capitalize() for client in *arr*: if client\_to\_change == client\['name']: client\_index = *arr*.index(client) #Obtenemos el índice donde esta nuestro diccionario *arr*.pop(client\_index) #Eliminamos el diccionario del array new\_client = { 'name': \_get\_client\_field('name'), 'company': \_get\_client\_field('company'), 'email': \_get\_client\_field('email'), 'position': \_get\_client\_field('position'), } *arr*.insert(client\_index, new\_client) #Agregamos el cliente actualizado en la posición anterior else: print("The client is not in the list") #if client\_to\_change in arr: # client\_index = arr.index(client\_to\_change) # arr.pop(client\_index) # client\_updated = "" #while client\_updated == "" or client\_updated == " ": # client\_updated = input("What is the new name of the client? ").capitalize() #arr.insert(client\_index, client\_updated) #print(arr) #print() #else: # print("The client is not in the list") *def* creat\_cliente(*arr*): client = { 'name': \_get\_client\_field('name'), 'company': \_get\_client\_field('company'), 'email': \_get\_client\_field('email'), 'position': \_get\_client\_field('position'), } if client not in *arr*: *arr*.append(client) else: print("The client is already in the list") *def* list\_clients(*arr*): for idx, client in <u>enumerate</u>(*arr*): print(f'{idx}: {client\["name"]}, {client\["company"]}, {client\["email"]}, {client\["position"]}') *def* delete\_client(*arr*): client\_name = input("What is the client name of the cliente you want to delete? ").capitalize() for client in *arr*: if client\_name == client\['name']: *arr*.remove(client) print() else: print("The client is not in the list") *def* welcome\_message(): print("WELCOME TO PLATZI VENTAS") print("\*"\*50) print("Press \[S] to start.")   *def* menu(): print("What would you like to do today?") print("\[C]reate Client") print("\[R]ead list of Clients") print("\[U]pdate Client") print("\[D]elete Client") print("\[E]xit")   *def* run(): clients = \[ { 'name': "Pablo", 'company': "Google", 'email': "pablo@google.com", 'position': "Software Engineer" }, { 'name': 'Juan', 'company': 'Maxidespensa', 'email' : 'Juan@maxi.com', 'position' : 'Sofware Engineer' } ] menu\_activo = 0 welcome\_message() user\_cmd = input().capitalize() if user\_cmd == "S": menu\_activo = 1 while menu\_activo: menu() user = input().capitalize() if user == "C": creat\_cliente(clients) elif user == "R": list\_clients(clients) elif user == "U": update\_client(clients) elif user == "D": delete\_client(clients) elif user == "E": menu\_activo = 0 else: menu\_activo = 0 if \_\_name\_\_ == '\_\_main\_\_': run()
Quizá fui un tanto redundante, pero lo sentí legible, aquí mi código y pues regalenme un like, si les agradó la solución.
import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position':'Software engineer', }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position':'Data engineer', } ] def create_client(client): global clients #global permite jalar las variables globales del scoop if client not in clients: clients.append(client) else: print('Client already is in the client\'s list') def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid = idx, name = client['name'], company = client['company'], email = client['email'], position = client['position'])) def delete_client(client_name): for i in range(0, len(clients)): if client_name == clients[i]['name']: clients.remove(clients[i]) break else: print('Client is not in clients list') def update_client(client_name, updated_name, updated_data): for i in range(0, len(clients)): if client_name == clients[i]['name']: clients[i] = updated_data else: print('Client is not in clients list') def search_client(client_name): for i in range(0, len(clients)): if client_name != clients[i]['name']: continue else: return True def _get_client_field(field_name): field = None while not field: field = input('What is the client {}? '.format(field_name)) return field def _get_client_name(): client_name = None while not client_name: client_name = input('Whats is the client name? ') if client_name == 'exit': client_name = None break if not client_name: sys.exit() return client_name def _print_welcome(): print('WELCOME TO PLATZI VENTAS') print('*' * 50) print('What would you like to do today?') print('[C]reate client') print('[L]ist client') print('[D]elete client') print('[U]pdate client') print('[S]earch client') if __name__ == '__main__': _print_welcome() command = input() command = command.upper() if command == 'C': client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } create_client(client) list_clients() elif command == 'L': list_clients() elif command == 'D': client_name = _get_client_name() delete_client(client_name) list_clients() elif command == 'U': client_name = _get_client_name() updated_name = input('What is the updated client name?: ') updated_data = { 'name': updated_name, 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } update_client(client_name, updated_name, updated_data) list_clients() elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found: print('The client is in the client\'s list') else: print('The client: {} is not in the client\'s list'.format(client_name)) else: print('invalid comand')
Mi codigo, le añadi un retoque a la funcipon Delete, para evitar errores, haciendo que el usuario confirme la eliminación
import sys clients = [ { 'name' : 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position' : 'Sofware engineer' }, { 'name' : 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position' : 'Data engineer' } ] def _get_client_field(field_name): field = None while not field: field = input(f'What is the client {field_name}? ') return field def create_client(client_name): global clients if client_name not in clients: clients.append(client_name) else: print('Client already is in the client\'s list') def update_client(update_client_name, client_name): global clients for client in clients: if updated_client_name in client['name']: name = client_name company = _get_client_field('company') email = _get_client_field('email') position = _get_client_field('position') client.update({'name' : name, 'company' :company, 'email': email, 'position': position}) else: print('Client is not in clients list') def delete_client(client_name): for client in clients: if client_name == client['name']: command = input(f'Are you sure you want to eliminate {client_name}?(Y/n) ') if command == 'Y': clients.remove(client) else: sys.exit() else: print('Client is not in clients list') def seach_client(client_name): for client in clients: if client_name == client['name']: return True return False def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid = idx, name = client['name'], company = client['company'], email = client['email'], position = client ['position'] )) def _print_welcome(): print('WELCOME TO QUEIS VENTAS') print('*' * 5) print('What wouls you like to do today?') print('[C]reate client') print('[U]pdate client') print('[D]elete client') print('[S]earch client') if __name__ == '__main__': _print_welcome() command = input().upper() if command == 'C': client = { 'name' : _get_client_field('name'), 'company' : _get_client_field('company'), 'email' : _get_client_field('email'), 'position' : _get_client_field('position'), } create_client(client) list_clients() elif command == 'D': client_name = _get_client_field('[D]eleted') delete_client(client_name) list_clients() elif command == 'U': updated_client_name = _get_client_field('to [U]pdate') client_name = _get_client_field('new') update_client(updated_client_name, client_name) list_clients() elif command == 'S': client_name = _get_client_field('[S]earch') found = seach_client(client_name) if found: print('The client is in the clien\'s list') else: print(f'The client: {client_name} is not in out client\'s list') else: print('Invalid Command')
Mi verisón de las funciones UPDATE, DELETE y SEARCH: UPDATE:
def update_client(client_name): state = 0 for idx, client in enumerate(clients): if client_name == client['name']: a = '''Choose a number to define which field you will update: 1) All of them 2) Name 3) Company 4) Email 5) Position : ''' ask = int(input(a)) if ask == 1: all_them = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } clients[idx] = all_them elif ask == 2: name = _get_client_field('name') clients[idx]['name'] = name elif ask == 3: company = _get_client_field('company') clients[idx]['company'] = company elif ask == 4: email = _get_client_field('email') clients[idx]['email'] = email elif ask == 5: position = _get_client_field('position') clients[idx]['position'] = position else: state = 1 if state == 1: print('Client is not in clients list')
DELETE
def delete_client(client_name): state = 0 for idx, client in enumerate(clients): if client_name == client['name']: del clients[idx] else: state = len(clients) if state == len(clients): print('Client is not in clients list')
SEARCH:
def search_client(client_name): for idx, client in enumerate(clients): if client_name != client['name']: continue else: return True
Solucion al reto, aunque en el Update no solo se actualizo el nombre sino toda la informacion
def update_client(client_name, updated_client): global clients for key, client in enumerate(clients): if client["name"] == client_name: clients[key] = updated_client break else: print("Client is not in the client's list") def delete_client(client_name): global clients for key, client in enumerate(clients): if client["name"] == client_name: del clients[key] break else: print("Client is not in the client's list") def search_client(client_name): for client in clients: if client['name'] == client_name: return True return False # Actualizacion client_name = _get_client_name() client = { "name": _get_client_field("name", is_new=True), "company": _get_client_field("company", is_new=True), "email": _get_client_field("email", is_new=True), "position": _get_client_field("position", is_new=True) } update_client(client_name, client)
import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position': 'software engineer' }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'Ricardo@facebook.com', 'position': 'data engineer' } ] def create_client(client): global clients if client not in clients: clients.append(client) else: print('Client already is in the client\'s list') def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {position}'.format( uid=idx, name=client['name'], company=client['company'], position=client['position'] )) def print_welcome(): print('Welcome to platzi sales') print('*' * 50) print('What would you like doing today?') print('[C]reate client: ') print('[L]ist clients: ') print('[U]pdate client') print('[D]elete client: ') print('[S]earch client') def _get_client_field(field_name): field = None while not field: field = input('What is the client {}: ?'.format(field_name)) return field def _get_client_name(): client_name = None while not client_name: client_name = input('What is the client name? :') if client_name == 'exit': client_name = None break if not client_name: sys.exit() return client_name def _get_message(kind_of_message): if kind_of_message == 'refuse' : return print('Client is not in clients list') elif kind_of_message == 'isInList': return print('This client name is in the client list') elif kind_of_message == 'success': return print('success') def update_client(client_name): global clients for client in clients: if client['name'] == client_name: index = clients.index(client) client = _get_client_object() clients[index] = client def _delete_client(client_name): global clients for client in clients: if client['name'] == client_name: index = clients.index(client) clients.pop(index) _get_message('success') break else: _get_message('refuse') def search_client(client_name): global clients for client in clients: if client['name'] != client_name: continue else: return True def _get_client_object(): client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position') } return client if __name__ == '__main__': print_welcome() command = input().upper() if command == 'C': client = _get_client_object() # client_name = _get_client_name() create_client(client) list_clients() elif command == 'D': client_name = _get_client_name() _delete_client(client_name) list_clients() elif command == 'U': client_name = _get_client_name() update_client(client_name) list_clients() elif command == 'L': list_clients() elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found: _get_message('isInList') else: print('The client {} is not our client\'s list'.format(client_name)) else: print('Invalid comman')
<code> import sys #variable global clients=[ { 'name': 'pablo', 'company': 'google', 'email': 'pablo@gamail.com', 'position': 'software engineer' }, { 'name': 'ricardo', 'company': 'facebook', 'email': 'ricardo@gamail.com', 'position': 'data engineer' } ] #crear cliente def create_client(client_name): global clients if client not in clients: clients.append(client) else: print('client already is in client\'s list') #Listar clintes def list_clients(): for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid=idx, name = client['name'], company=client['company'], email=client['email'], position=client['position'] )) #optiene el campo del cliente def _get_client_field(field_name): field = None while not field: field = input('what is the client {}?'.format(field_name)) return field #devuelve el indice del cliente def _get_index_client(): client_name=None client_index=None while not client_name: client_name=str(input('what is the client name? =>')) if client_name == 'exit': client_name=None break if not client_name: sys.exit() for idx, client in enumerate(clients): if client['name'] == client_name: client_index=idx return client_index #recoge la opcion de update client def _get_option(): option=None while not option: option=str(input('=> ')).upper() if option == 'exit': option=None break elif option != 'N' and option != 'C' and option != 'E' and option != 'P': print('Invalid command') option=None if not option: sys.exit() return option #recoge nuevo valor def _get_value(): value = None while not value: value=str(input(' Enter new value => ')) if value == 'exit': value=None break if not value: sys.exit() return value #menu de opciones a actualizar def _print_option(): print("""Choose the option you want to modify [N]ame [C]ompany [E]mail [P]osition """) #actualizar clientes def update_client(client_index): global clients for idx, client in enumerate(clients): if idx == client_index: _print_option() option=_get_option() if option=='N': client['name']= _get_value() print('Name modified') elif option=='C': client['company']=_get_value() print('Company modified') elif option=='E': client['email']=_get_value() print('Email modified') elif option == 'P': client['position']=_get_value() print('Client modified') #busca un cliente def search_client(): check = _get_index_client() return check #borrar clientes def delete_clients(): global clients index = _get_index_client() if index != None: client=clients[index] print('client {} deleted'.format(client['name'])) del clients[index] else: _get_not_client() #muestra el menu def _print_welcome(): print('WELCOME TO PLATZI VENTAS') print('*' * 50) print('what would you like to do today?') print('[C]reate client') print('[U]pdate client') print('[L]ist client ') print('[D]elete client') print('[S]earch client') #evita repetir codigo def _get_not_client(): return print('The client is not in our Client\'s list') #inicio main if __name__ == '__main__': _print_welcome() command =str(input('=> ')).upper() if command == 'C': client = { 'name': _get_client_field('name'), 'company':_get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position') } create_client(client) list_clients() elif command =='D': delete_clients() list_clients() elif command =='U': client_index = _get_index_client() update_client(client_index) list_clients() elif command =='S': found = search_client() if found != None: print('The client is in the client\'s list') print(clients[found]) else: _get_not_client() elif command == 'L': list_clients() else: print('Invalid command')
Bueno aqui mi codigo, espero les sirva de algo, Saludos !
import sys clients=[ { 'name':'pablo', 'company':'Google', 'email':'pablo@google.com', 'position':'Software Ingenier' }, { 'name':'Ricardo', 'company':'Facebook', 'email':'ricardo@facebook.com', 'position':'Data engineer' } ] def _exist_client(client): global clients total_clientes=range(len(clients)) for x in total_clientes: id=x if client['name'] in clients[x]['name']: return True,id else: continue return False,id def create_client(client): clients.append(client) def client_not_list(): print('Client in not in clients list') def list_clients(): print('|id| |Name| |Company| |Email| |Position|') print('*'*50) for idx,client in enumerate(clients): print('{uid}|{name}|{company}|{email}|{position}'.format( uid=idx, name=client['name'], company=client['company'], email=client['email'], position=client['position'] ) ) def updated_client(client_name,updated_client_name,id): global clients clients[id]['name']=updated_client_name clients[id]['company']=_get_client_field('company') clients[id]['email']=_get_client_field('email') clients[id]['position']=_get_client_field('position') def delete_client(id): global clients clients.pop(id) def search_client(client): global clients total_clientes=range(len(clients)) for x in total_clientes: if client['name'] in clients[x]['name']: id=x return True,x id=x return False,id def _print_welcome(): print('Welcome To Platzi Ventas') print('*'*50) print('What would you like to do today?') print('(C)reate client') print('(L)ist') print('(U)pdate client') print('(D)elete client') print('(S)earch client') def _get_client_field(field_name): field =None while not field: field = input('What is the client {}?'.format(field_name)) return field def _get_client_name(): client_name=None while not client_name: client_name=input('What is the Client name?') if client_name=='exit': client_name=None break if not client_name: sys.exit() return client_name if __name__=='__main__': _print_welcome() command =input() command = command.upper(); if command=='C': client={ 'name':_get_client_name() } TrueFalse,id=_exist_client(client) if TrueFalse==False: client['company']=_get_client_field('company') client['email']=_get_client_field('email') client['position']=_get_client_field('position') create_client(client) else: print('Client already in the client\'s list') list_clients() elif command=='L': list_clients() elif command=='D': client_name={ 'name':_get_client_name() } TrueFalse,id=_exist_client(client_name) if TrueFalse==True: delete_client(id) else: print('The client: {} is not in our client\'s list'.format(client_name['name'])) list_clients() elif command=='S': client_name={ 'name':_get_client_name() } TrueFalse,id=search_client(client_name) if TrueFalse==True: print('The client is in the client\'s list') print('{uid}|{name}|{company}|{email}|{position}'.format( uid=id, name=clients[id]['name'], company=clients[id]['company'], email=clients[id]['email'], position=clients[id]['position'] ) ) else: print('The client: {} is not in our client\'s list'.format(client_name['name'])) elif command =='U': client={ 'name': _get_client_name() } TrueFalse,id=_exist_client(client) if TrueFalse==False: client_not_list() else: updated_client_name=input('What is the updated client name ?') updated_client(client,updated_client_name,id) list_clients() else: print('Invalid command')```
<code> import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': 'pablo@google.com', 'position': 'Software engineer', }, { 'name': 'Ricardo', 'company': 'Amazon', 'email': 'ricardo@amazon.com', 'position': 'Data engineer', } ] def create_client(client): #se mete la variable client en la funcion global clients #si el cliente no esta en la lista de clientes: if client not in clients: clients.append(client) else: print('Client already is in the client\'s list ') def list_clients(): global clients for idx, client in enumerate(clients): print('{uid} | {name} | {company} | {email} | {position}'.format( uid=idx, name=client['name'], company=client['company'], email=client['email'], position=client['position'])) def update_client(old_data, new_data): global clients for client in clients: for key, values in client.items(): if old_data in values: for data in new_data: clients.remove(client) create_client(new_data) return True else: return False def update_procces(field, old_data, new_data): cmd = update_client(old_data, new_data) if cmd is True: list_clients() else: print(f'{field} not valid') def delete_client(client_name): global clients for client in clients: for data in dicts.values(): if client_name in data: clients.remove(client) return True def search_client(client_name): global clients for client in clients: for data in client.values(): if client_name == data: return True def _print_welcome(): print('\nBienvenidos a Platzi Ventas') print('+' * 27) print('What to do doing today?') print('[C]reate Client') print('[L]ist clients') print('[U]pdate client') print('[S]earch Client') print('[D]elete Client\n') def _get_client_field(field_name): field = None while not field: field = input('What is the client {}? '.format(field_name)) return field def _get_client_field_updated(field_name): field = None while not field: field = input('What is the new client {}? '.format(field_name)) return field def _get_client_name(): client_name = None while not client_name: client_name = input('What is the client name? ') if client_name.lower() == 'exit': client_name = None if not client_name: sys.exit() return client_name if __name__ == "__main__": _print_welcome() command = input() if command.upper() == 'C': client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position'), } create_client(client) list_clients() elif command.upper() == 'L': list_clients() elif command.upper() == 'D': client_name = _get_client_name() deleted = delete_client(client_name) if deleted is True: print('Deleted') list_clients() else: print('Client is not in the client\'s list') elif command.upper() == 'U': old_data = _get_client_field('name') new_data = {'name': _get_client_field_updated('name'), 'company': _get_client_field_updated('company'), 'email': _get_client_field_updated('email'), 'position': _get_client_field_updated('position'), } field = 'name' update_procces(field, old_data, new_data) elif command.upper() == 'S': client_name = _get_client_name() found = search_client(client_name) if found: print('The Client is in the client\'s list') else: print('The client: {} is not in our client\'s list'.format(client_name)) else: print('Invalid command')
# -*- coding:utf-8 -*- import sys clients = [ { 'name': 'Pablo', 'company': 'Google', 'email': "pablo@google.com", "position": "Software engineer" }, { 'name': 'Ricardo', 'company': 'Facebook', 'email': 'ricardo@facebook.com', 'position': 'Data engineer' } ] def create_client(client): global clients if client not in clients: clients.append(client) print("The client {} has been created in our list.".format(client['name'])) list_clients() else: print("The client {} is alredy registred.".format(client['name'])) list_clients() def delete_client(client_name): global clients found = None for idx, client in enumerate(clients): if client['name'] == client_name: clients.pop(idx) print("The client {} has been removed from our list.".format(client_name)) list_clients() found = True else: found = False return found def list_clients(): print("This is our client list: ") for idx, client in enumerate(clients): print('{uid}: | {name} | {company} | {email} | {position} |'.format( uid=idx, name=client['name'], company=client['company'], email=client['email'], position=client['position'] )) print("*" * 50) def search_client(client_name): found = None for idx, client in enumerate(clients): if client['name'] != client_name: found = False continue else: found = True break if found: print('The client {} is on our list, in the index {}.'.format(client_name, idx)) list_clients() else: _not_client() return found def update_client(client_name): found = search_client(client_name) if found is True: print("What data do you want to update? ") print("[N]ame?") print("[C]ompany?") print("[E]mail?") print("[P]osition?") print("*" * 50) field_update = input() field_update = field_update.upper() if field_update == "N": for idx, client in enumerate(clients): if client_name == client['name']: client['name'] = _get_client_field('name') list_clients() elif field_update == "C": for idx, client in enumerate(clients): if client_name == client['name']: client['company'] = _get_client_field('company') list_clients() elif field_update == "E": for idx, client in enumerate(clients): if client_name == client['name']: client['email'] = _get_client_field('email') list_clients() elif field_update == "P": for idx, client in enumerate(clients): if client_name == client['name']: client['position'] = _get_client_field('position') list_clients() else: print("Invalid command, try again.") else: _not_client() def _print_wellcome(): print("WELLCOME TO NEOPOLIX") print("*" * 50) print("What would you like to do today?") print("[C]reate Client") print("[D]elete Client") print("[L]ist Client") print("[S]earch Client") print("[U]pdate Client") print("*" * 50) def _not_client(): print("Client is Not in clients list") def _get_client_field(field_name): field = None while not field: field = input('What is the client {}? '.format(field_name)) return field if __name__ == '__main__': _print_wellcome() command = input() command = command.upper() if command == "C": client = { 'name': _get_client_field('name'), 'company': _get_client_field('company'), 'email': _get_client_field('email'), 'position': _get_client_field('position') } create_client(client) elif command == "L": list_clients() elif command == "D": client_name = _get_client_field('name') delete_client(client_name) elif command == "U": client_name = _get_client_field('name') update_client(client_name) elif command == "S": client_name = _get_client_field('name') found = search_client(client_name) else: print("Invalid command")