bradi
bradi

Reputation: 97

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?

Upvotes: 4

Views: 2184

Answers (3)

ldavid
ldavid

Reputation: 2552

How about this?

>>> d = {(min(x, y), max(x, y)): float(z) for x, y, z in a}
>>> d
{('16', '18'): 0.4, ('0', '1'): 0.5, ('1', '3'): 0.7}
>>> for (x, y), z in d.items():
...     print('%s, %s: %f' % (x, y, z))

Upvotes: 1

Patrick Maupin
Patrick Maupin

Reputation: 8137

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)

Upvotes: 3

DSM
DSM

Reputation: 353059

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}

Upvotes: 2

Related Questions