conversion of list of list of tuples to dict not working as expected

Viewed 69

I am trying to create the dict for this list of lists contains tuples. The purpose is to filter the needed tuples into the final list.

What I have tried so far:

dict_1 = dict()
for val,sim in result:
    dict_1.setdefault(val, [])


print(result)

It works fine when I look into result and unpack two values (val,sim). But every time it is not the same case i will get, there could be multiple values to unpack and then it gives this error:

ValueError: too many values to unpack (expected 2).

How can make the above loop for val,sim in result: flexible?

This is the input format:

[[(1.0, 2481), (0.125, 5)], [(1.0, 2481), (0.10526315789473684, 1), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 2)], [(1.0, 2481), (0.11764705882352941, 2), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 1)], [(1.0, 2481), (0.13333333333333333, 3), (0.0, 5), (0.0, 4), (0.0, 2), (0.0, 1)], [(1.0, 2481), (0.1, 4), (0.0, 5), (0.0, 3), (0.0, 2), (0.0, 1)]]

My ultimate goal is to make the dict first and then start filtering the tuples i am only interested in the tuples [(value,sim), (value,sim)] which have a specific value sim but before doing that I am stuck in above part.

Desired output:

[(1.0, 2481), (0.125, 5), (0.10526315789473684, 1),(0.11764705882352941, 2), (0.13333333333333333, 3), (0.1, 4)]

I am just a beginner. I understand this might not be the correct way to ask question. But any kind of little guidance in right direction would be appreciated!

1 Answers

You can try nested slicing:

a = [[(1.0, 2481), (0.125, 5)], 
     [(1.0, 2481), (0.10526315789473684, 1), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 2)], 
     [(1.0, 2481), (0.11764705882352941, 2), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 1)], 
     [(1.0, 2481), (0.13333333333333333, 3), (0.0, 5), (0.0, 4), (0.0, 2), (0.0, 1)], 
     [(1.0, 2481), (0.1, 4), (0.0, 5), (0.0, 3), (0.0, 2), (0.0, 1)]]

b = [a[0][0]] + [i[1] for i in a]

print(b)

Output:

[(1.0, 2481), 
 (0.125, 5), 
 (0.10526315789473684, 1), 
 (0.11764705882352941, 2), 
 (0.13333333333333333, 3), 
 (0.1, 4)]
Related