I have a big set of data formatted likely in this way:
data=[
(a1,b1,[(alfa,1,2,3),(alfa,4,5,6),(alfa,1,4,6),(gamma,2,4,3),(gamma,31,4,6),(delta,3,3,4),(alfa,2,4,6)]),
(a1,b2,[(beta,4,2,6),(beta,1,5,5),(theta,1,0,6)]),
........,
........
]
i’m trying to extract from data recursively the "alfa", beta gamma, thetalike a kind of index/referral and the rest of more internal tuple recombined as a matrix (list of list) thus obtained by epurate from their 1st element (the new index). The outer elements a1,b1,b2 are easy to manipulate and will take part for further manipulations. Need something like :
'a1' 'b1' 'alfa' [[1,2,3]
[4,5,6]
[1,4,6]
[2,4,6]]
'gamma' [[2,4,3]
[31,4,6]]
'delta' [[3,3,4]]
'a1' 'b2' 'beta' [[4,2,6]
[1,5,5]]
'theta' [[1,0,6]]
I was using thinking to create many keys of a dict, as per the indexes (the alfa,beta or whater I will find) and populate a referred list to each of the keys by append(). here what I’ve made:
tmp ={}
data = []
for i in market:
for j in i[2]:
tmp[j[0]]=data.append([j[1],j[2],j[3]])
..but the new index tmp[j[0]] will ereditate the whole old values of other indices..or doesn’t work
>Solution :
You have
data = [
('a1','b1',[('alfa',1,2,3),('alfa',4,5,6),('alfa',1,4,6),('gamma',2,4,3),('gamma',31,4,6),('delta',3,3,4),('alfa',2,4,6)]),
('a1','b2',[('beta',4,2,6),('beta',1,5,5),('theta',1,0,6)]),
# and so on...
]
You want to convert this into a dictionary, where the keys are three-element tuples and the values are matrices.
Recognize that each item in this list is a tuple.
- In this item, the first two elements
item[0:2]are the first two elements of the key you want to use in your dictionary. - The third element
item[2]is a list. Each element of this list is a tuple, containing:- The first element
elem[0]is the third element of the key - The remaining elements
elem[1:]give you a new row in your matrix
- The first element
So from every elem you encounter in item[2], you need to extract the first item to create the key you are looking for in your dict. Then, check if the key already exists in the dict. If it doesn’t, create a new list with row as its first element. If it does, then simply .append() the new row to the list.
dict_data = {}
for item in data:
k1, k2 = item[0:2]
for elem in item[2]:
k3 = elem[0]
row = elem[1:]
if (k1, k2, k3) in dict_data:
dict_data[k1, k2, k3].append(row) # or .append(list(row))
else:
dict_data[k1, k2, k3] = [row] # or [list(row)]
Which gives the following dict_data:
{('a1', 'b1', 'alfa'): [
(1, 2, 3),
(4, 5, 6),
(1, 4, 6),
(2, 4, 6)
],
('a1', 'b1', 'gamma'): [
(2, 4, 3),
(31, 4, 6)
],
('a1', 'b1', 'delta'): [(3, 3, 4)],
('a1', 'b2', 'beta'): [(4, 2, 6), (1, 5, 5)],
('a1', 'b2', 'theta'): [(1, 0, 6)]}
If you want rows to be lists rather than tuples, simply convert them before adding them (as shown by the comments in the code above)