Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack list as key in dictionary -- Python 3.4

I'm attempting to sort two values drawn from the indices of a list so that the key in a dictionary is alway some pair of values (x,y) such that x < y.

Given, for example:

a = [['0', '1', '.5'], ['3', '1', '.7'], ['18','16','.4']]

I would like d[(16, 18)] = .4, with all numbers in the key turned into integers in order from smallest to largest, and the value as a float.

Here's what I've tried:

a = [['0', '1', '.5'], ['3', '1', '.7'], ['18','16','.4']]

d = {}
for i in a:
    b = sorted([int(i[0]), int(i[1])])
    d[*b] = float(i[2])

I read about unpacking a list here and thought I'd give it a go, but I'm getting a SyntaxEror on the asterisk. Help?

like image 565
bradi Avatar asked Nov 16 '25 14:11

bradi


2 Answers

You can use a tuple as an index to a dict, but it is not a parameter, so the asterisk syntax doesn't apply:

a = [['0', '1', '.5'], ['3', '1', '.7'], ['18','16','.4']]

d = {}

for (x,y,z) in a:
    d[tuple(sorted(int(i) for i in (x, y)))] = float(z)

print(d)
like image 113
Patrick Maupin Avatar answered Nov 18 '25 06:11

Patrick Maupin


As you've discovered, you can't use *-unpacking within an index like that. But your code should work if you use tuple(b) instead of *b (we can't use b itself, because lists aren't hashable and so can't be used as dictionary keys.)

>>> for i in a:
        b = sorted([int(i[0]), int(i[1])])
        d[tuple(b)] = float(i[2])
...     
>>> d
{(0, 1): 0.5, (1, 3): 0.7, (16, 18): 0.4}
like image 31
DSM Avatar answered Nov 18 '25 05:11

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!