Dado un diccionario anidado, la tarea es eliminar los diccionarios duplicados del diccionario. A continuación se presentan algunos métodos para completar la tarea dada.
Método n.º 1: uso del método ingenuo
# Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{'a':2, 'b':3}, 'd':{'a':2, 'b':7}} # printing initial_dictionary print ("initial dictionary", str(ini_dict)) # code to remove duplicates result = {} for key, value in ini_dict.items(): if value not in result.values(): result[key] = value # printing result print ("result", str(result))
diccionario inicial {‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}, ‘a’: {‘c’: 2, ‘b’: 1}, ‘b’: {‘c’: 2, ‘b’: 1}}
resultado {‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: { ‘a’: 2, ‘b’: 7}, ‘a’: {‘c’: 2, ‘b’: 1}}
Método n.º 2: usar ordenados y establecidos
# Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{'a':2, 'b':3}, 'd':{'a':2, 'b':7}} # printing initial_dictionary print ("initial dictionary", str(ini_dict)) # code to remove duplicates keep = set({repr(sorted(value.items())):key for key, value in ini_dict.items()}.values()) for key in list(ini_dict): if key not in keep: del ini_dict[key] # printing result print ("result", str(ini_dict))
diccionario inicial {‘a’: {‘b’: 1, ‘c’: 2}, ‘b’: {‘b’: 1, ‘c’: 2}, ‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}}
resultado {‘b’: {‘b’: 1, ‘c’: 2}, ‘c’: { ‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}}
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