Dada una lista de diccionarios, la tarea es ordenar el diccionario por fecha. Veamos algunos métodos para resolver la tarea.
Método #1: Usar un enfoque ingenuo
# Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial list print ("initial list : ", str(ini_list)) # code to sort list on date ini_list.sort(key = lambda x:x['d.o.b']) # printing final list print ("result", str(ini_list))
lista inicial: [{‘name’: ‘akash’, ‘dob’: ‘1997-03-02’}, {‘name’: ‘manjeet’, ‘dob’: ‘1997-01-04’}, {‘ nombre’: ‘nikhil’, ‘dob’: ‘1997-09-13’}]
resultado [{‘nombre’: ‘manjeet’, ‘dob’: ‘1997-01-04’}, {‘nombre’: ‘akash’, ‘dob’: ‘1997-03-02’}, {‘nombre’ : ‘nikhil’, ‘dob’: ‘1997-09-13’}]
Método #2: Usar datetime.strptime
ylambda
# Python code to demonstrate # sort a list of dictionary # where value date is in a string from datetime import datetime # Initialising list of dictionary ini_list = [{'name':'akshat', 'd.o.b':'1997-09-01'}, {'name':'vashu', 'd.o.b':'1997-08-19'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial list print ("initial list : ", str(ini_list)) # code to sort list on date ini_list.sort(key = lambda x: datetime.strptime(x['d.o.b'], '%Y-%m-%d')) # printing final list print ("result", str(ini_list))
lista inicial: [{‘dob’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘dob’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘ fecha de nacimiento’: ‘1997-01-04’, ‘nombre’: ‘manjeet’}, {‘fecha de nacimiento’: ‘1997-09-13’, ‘nombre’: ‘nikhil’}]
resultado [{‘dob’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘dob’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘dob’ : ‘1997-09-01’, ‘nombre’: ‘akshat’}, {‘dob’: ‘1997-09-13’, ‘nombre’: ‘nikhil’}]
Método #3: Usaroperator.itemgetter
# Python code to demonstrate # sort a list of dictionary # where value date is in string import operator # Initialising list of dictionary ini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet', 'd.o.b':'1997-01-04'}, {'name':'nikhil', 'd.o.b':'1997-09-13'}] # printing initial list print ("initial list : ", str(ini_list)) # code to sort list on date ini_list.sort(key = operator.itemgetter('d.o.b')) # printing final list print ("result", str(ini_list))
lista inicial: [{‘dob’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘dob’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘ fecha de nacimiento’: ‘1997-09-13’, ‘nombre’: ‘nikhil’}]
resultado [{‘dob’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘dob’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘dob’ : ‘1997-09-13’, ‘nombre’: ‘nikhil’}]
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA