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?
CodePudding user response:
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]
.