Dada una lista de diccionarios, la tarea es convertirla en un solo diccionario, es decir, aplanar una lista de diccionarios.
A continuación se presentan algunos métodos para resolver la tarea dada.
Método n.º 1: uso del método ingenuo
Python3
# Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionary print ("initial dictionary", str(ini_dict)) # code to flatten list of dictionary res = {} for d in ini_dict: res.update(d) # printing result print ("result", str(res))
Producción:
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}] result {'b': 2, 'a': 1, 'c': 3}
Método #2: Usar la comprensión de dictado
Python3
# Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionary print ("initial dictionary", str(ini_dict)) # code to flatten list of dictionary res = {k: v for d in ini_dict for k, v in d.items()} # printing result print ("result", str(res))
Producción:
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}] result {'a': 1, 'c': 3, 'b': 2}
Método #3: Usar reducir
Python3
# Python code to demonstrate # to flatten list of dictionaries from functools import reduce # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionary print ("initial dictionary", str(ini_dict)) # code to flatten list of dictionary res = reduce(lambda d, src: d.update(src) or d, ini_dict, {}) # printing result print ("result", str(res))
Producción:
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}] result {'a': 1, 'c': 3, 'b': 2}
Método #4: Usarcollections.ChainMap
Python3
# Python code to demonstrate # to flatten list of # dictionaries from collections import ChainMap # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # printing initial dictionary print ("initial dictionary", str(ini_dict)) # code to flatten list of dictionary res = ChainMap(*ini_dict) # printing result print ("result", str(res))
Producción:
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}] result ChainMap({'a': 1}, {'b': 2}, {'c': 3})
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