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

407
Visualizações
Dictionary with tuple keys and two lists as values, where a value is added to just one of the lists

I have a set of integers in the form of a tuple forming my keys (a,b). I need to construct a dictionary where, for each key, a value (float) is put in one of the two lists that acts as pair-value:

(a,b) : [x_list,y_list]

I am constructing the dictionary from a txt file where each line has the tuple (a,b) and ONE of either x or y-type value that should be added to the list. However, I fail to understand how this can be done.

To be more precise:

if the txt file contains:

15,17,x_type,-1.1
15,17,y_type,44
1,2,y_type,-0.38
15,17,y_type,5

the dictionary should produce

d: {(1,2): [[], [-0.38]] , (15,17): [[-1.1], [5,44]]

What I am trying:

example = ['15,17,x_type,-1.1','15,17,y_type,44','1,2,y_type,-0.38','15,17,y_type,5']

for _ in example:
    [a,b,val_type,val] = _.split(',')
    if val_type == 'x_type':
       d[(a,b)] = [val,]
    if val_type == 'y_type':
       d[(a,b)] = [,val]

The syntax allows for [x,], but does not for [,y]. Why?

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

0

Lists can contain trailing commas. [x,] is the same as [x]. To append to a specific nested list, select the one you want by index:

if type == 'x_type':
   d[(a,b)][0].append(x)
elif type == 'y_type':
   d[(a,b)][1].append(y)

This assumes that you make a new nested list as soon as you encounter a key:

if (a, b) not in d:
    d[a, b] = [[], []]

Another nice syntactic trick is that anything with commas in an indexing expression is interpreted as a tuple. That means that you can write d[(a, b)] as d[a, b].

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