Quiero imprimir un diccionario dentro de una lista como esta:
[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]` No quiero citas en name e id . Sin embargo, los quiero en la parte de valores de ese diccionario.
Tendría que escribir su propia función de formato para hacer eso.
Aquí hay una función peluda pero concisa que hace lo que quieres:
def pretty_print(data): return '[%s]' % ', '.join( '{%s}' % ', '.join( '%s : %r' % (key, value) for key, value in item.items() ) for item in data )Entonces el siguiente código:
print(pretty_print([ {'name': 'red', 'id': '1'}, {'name': 'yellow', 'id': '2'}, ]))imprimiría:
[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}]Puedes convertir esto como:
def fix_key_formatting(data_to_dump, keys_to_fix): return_str = json.dumps(data_to_dump) for key in keys_to_fix: return_str = return_str.replace('"%s":' % key, '%s:' % key) return return_str data = [ {'name': 'red', 'id': '1'}, {'name': 'yellow', 'id': '2'}, {'name': 'black', 'id': '3'}, {'name': 'white', 'id': '4'} ] import json print(fix_key_formatting(data, ('id', 'name'))) [ {name: "red", id: "1"}, {name: "yellow", id: "2"}, {name: "black", id: "3"}, {name: "white", id: "4"} ]Puede crear una clase simple con un método __repr__ para almacenar el valor de la cadena:
class String: def __init__(self, val): self.val = val def __repr__(self): return self.val data = [{'name' : 'red', 'id' : '1'}, {'name' : 'yellow', 'id' : '2'}, {'name' : 'black', 'id' : '3'}, {'name' : 'white', 'id' : '4'}] final_data = [{String(c):d for c, d in i.items()} for i in data]Producción:
[{name: 'red', id: '1'}, {name: 'yellow', id: '2'}, {name: 'black', id: '3'}, {name: 'white', id: '4'}]Para acceder a los valores de cadena, puede llamar al atributo:
string_values = [{c.val:d for c, d in i.items()} for i in final_data] Para aplicar la clase String a todas las claves en una estructura arbitraria, se puede usar la recursividad:
def convert_string(d): return {String(a):convert_string(b) if isinstance(b, dict) else b for a, b in d.items()} data = [{'name' : {'first':'blue', 'last':'black', 'known_ids':[34, 5, 12, 34]}, 'id' : '1'}, {'name' : 'yellow', 'id' : '2'}, {'name' : 'black', 'id' : '3'}, {'name' : 'white', 'id' : '4'}] new_data = list(map(convert_string, data))Producción:
[{name: {first: 'blue', last: 'black', known_ids: [34, 5, 12, 34]}, id: '1'}, {name: 'yellow', id: '2'}, {name: 'black', id: '3'}, {name: 'white', id: '4'}]