Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
Dictionary in list

I want to print a dictionary inside a list like this :

[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]`

I don't want quotations in name and id. However, I want them in the values portion of that dictionary.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You'd have to write your own formatting function to do that.

Here's a hairy but terse function that does what you want:

def pretty_print(data):
    return '[%s]' % ', '.join(
        '{%s}' % ', '.join(
            '%s : %r' % (key, value) for key, value in item.items()
        ) for item in data
    )

So the following code:

print(pretty_print([
    {'name': 'red', 'id': '1'},
    {'name': 'yellow', 'id': '2'},
]))

Would print:

[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}]
over 4 years ago · Santiago Trujillo Relatório

0

You can convert this like:

Code:

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

Test Code:

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')))

Results:

[
    {name: "red", id: "1"}, 
    {name: "yellow", id: "2"}, 
    {name: "black", id: "3"}, 
    {name: "white", id: "4"}
]
over 4 years ago · Santiago Trujillo Relatório

0

You can create a simple class with a __repr__ method to store the string value:

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]

Output:

[{name: 'red', id: '1'}, {name: 'yellow', id: '2'}, {name: 'black', id: '3'}, {name: 'white', id: '4'}]

To access the string values, you can call the attribute:

string_values = [{c.val:d for c, d in i.items()} for i in final_data]

To apply the class String to all keys in an arbitrary structure, recursion can be used:

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))

Output:

[{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'}]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda