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

217
Visualizações
Creating a "dictionary of sets"

I need to efficiently store data in something that would resemble a "dictionary of sets" e.g. have a dictionary with multiple (unique) values matching each unique key. The source of my data would be a (not very well) structured XML.

My idea is: I will look through a number of elements and find keys. If the key does not exist, add it to dictionary, if it already exists, just add a new value in the corresponding key.

And the result would be something like:

{
 'key1': {'1484', '1487', 1488', ...}
 'key2': {'1485', '1486', '1489', ...}
 'key3': {'1490', '1491', '1492', ...}
 ...
}

I need to add new keys on the go. I need to push unique values into each set. I need to be able to iterate through the whole dictionary.

I am not sure if this is even feasible, but if anybody could push me in the right direction, I would be more than thankful.

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

0

I'm not going to benchmark this but in my experience native dicts are faster

store = {}
for key, value in yoursource:
    try:
        store[key].add(value)
    except KeyError:
        store[key] = {value}
over 4 years ago · Santiago Trujillo Relatório

0

from collections import defaultdict
mydict = defaultdict(set)
mydict["key1"] |= {'1484', '1487', '1488'}

Iteration is just like the normal dict.

over 4 years ago · Santiago Trujillo Relatório

0

Using dict.setdefault() to create the key if it doesn't exist, and initialising it with an empty set:

store = {}
for key, value in yoursource:
    store.setdefault(key, set()).add(value)
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