Dadas dos listas de diccionarios, la tarea es fusionar estas dos listas de diccionarios en función de algún valor.
Método n.º 1: Usar defaultdict
y extend
para fusionar dos listas de diccionarios según school_id .
# Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List initialization Input1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Using defaultdict temp = defaultdict(list) # Using extend for elem in Input1: temp[elem['school_id']].extend(elem['roll_no']) for elem in Input2: temp[elem['school_id']].extend(elem['roll_no']) Output = [{"roll_no":y, "school_id":x} for x, y in temp.items()] # printing print(Output)
Producción:
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id ‘: 5, ‘roll_no’: [‘092112’]}]
Método #2: Usando extend()
solamente.
# Python code to merge two list of dictionaries # based on some value. # List initialization Input1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Iterating and using extend to convert for elm2 in Input2: for elm1 in Input1: if elm2['school_id'] == elm1['school_id']: elm1['roll_no'].extend(elm2['roll_no']) break else: Input1.append(elm2) # printing print(Input1)
Producción:
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id ‘: 5, ‘roll_no’: [‘092112’]}]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA