Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

405
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!