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?

Community
  • 1
  • 1
bradi
  • 97
  • 7

3 Answers3

3

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)
Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42
2

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}
DSM
  • 342,061
  • 65
  • 592
  • 494
1

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))
ldavid
  • 2,512
  • 2
  • 22
  • 38