Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
How to initialize defaultdict with keys?

I have a dictionary of lists, and it should be initialized with default keys. I guess, the code below is not good (I mean, it works, but I don't feel that it is written in the pythonic way):

d = {'a' : [], 'b' : [], 'c' : []}

So I want to use something more pythonic like defaultict:

d = defaultdict(list)

However, every tutorial that I've seen dynamically sets the new keys. But in my case all the keys should be defined from the start. I'm parsing other data structures, and I add values to my dictionary only if specific key in the structure also contains in my dictionary.

How can I set the default keys?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

From the comments, I'm assuming you want a dictionary that fits the following conditions:

  1. Is initialized with set of keys with an empty list value for each
  2. Has defaultdict behavior that can initialize an empty list for non-existing keys

@Aaron_lab has the right method, but there's a slightly cleaner way:

d = defaultdict(list,{ k:[] for k in ('a','b','c') })
over 4 years ago · Santiago Trujillo Denunciar

0

That's already reasonable but you can shorten that up a bit with a dict comprehension that uses a standard list of keys.

>>> standard_keys = ['a', 'b', 'c']
>>> d1 = {key:[] for key in standard_keys}
>>> d2 = {key:[] for key in standard_keys}
>>> ...
over 4 years ago · Santiago Trujillo Denunciar

0

If you're going to pre-initialize to empty lists, there is no need for a defaultdict. Simple dict-comprehension gets the job done clearly and cleanly:

>>> {k : [] for k in ['a', 'b', 'c']}
{'a': [], 'b': [], 'c': []}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda