0

Is it possible to create a dictonary in this style to give links to a model later on:

Pre = {['g1_i1', 'bd1']: ['i1_i2', 'i2_i1'], ['g1_i1', 'g2']: ['i1_i2', 'i2_i1'], ...}

My error code:

Pre = dict(zip(r, Pre_arr))
TypeError: unhashable type: 'list'

This is my code so far, but I have the problem that zip and dict are not working in this case. Do you know any other way of creating a dict like mentioned above or a kind of similar thing to pass values in this way?

links = ['g1_i1', 'i1_g1', 'bd1_i2', 'i2_bd1', 'g2_i3', 'i3_g2', 'i1_i2', 'i2_i1', 'i2_i3', 'i3_i2', 'i1_i5', 'i5_i1',
     'i3_i4', 'i4_i3', 'i4_i5', 'i5_i4', 'i4_p2', 'p2_i4', 'i5_p1', 'p1_i5']

psu = ['g1', 'g2', 'bd1']

Pre_arr = [['i1_i2', 'i2_i1'], ['i2_i3', 'i3_i2'], ['g1_i1', 'i1_g1'], ['i1_i2', 'i2_i1'], ['g1_i1', 'i1_g1'], ['i1_i2', 'i2_i1'], ['i2_i3', 'i3_i2'], ['i1_i2', 'i2_i1'], ['i2_i3', 'i3_i2'], ['i3_i4', 'i4_i3'], ['i2_i3', 'i3_i2'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5'], ['i2_i1', 'i1_i2'], ['i2_i3', 'i3_i2'], ['i2_i1', 'i1_i2'], ['g2_i2', 'i2_g2'], ['g2_i2', 'i2_g2'], ['g2_i2', 'i2_g2'], ['i2_i3', 'i3_i2'], ['g2_i2', 'i2_g2'], ['i2_i3', 'i3_i2'], ['i3_i4', 'i4_i3'], ['i2_i3', 'i3_i2'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5'], ['i2_i1', 'i1_i2'], ['i3_i2', 'i2_i3'], ['i2_i1', 'i1_i2'], ['i3_i2', 'i2_i3'], ['i3_i2', 'i2_i3'], ['i3_i2', 'i2_i3'], ['bd1_i3', 'i3_bd1'], ['bd1_i3', 'i3_bd1'], ['bd1_i3', 'i3_bd1'], ['i3_i4', 'i4_i3'], ['bd1_i3', 'i3_bd1'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5'], ['i4_i5', 'i5_i4'], ['i3_i4', 'i4_i3'], ['i4_i5', 'i5_i4'], ['i5_i6', 'i6_i5']]

r = []
w =[]
for i in links:
    w += i.split('_')
#print(w)

for j in range(0, len(w), 2):
    l2 = list((w[j], w[j+1]))
    for i in psu:
        if w[j] == i or w[j+1] == i:
            pass
        else:
            m = ('_'.join(l2))
            r.append([m, i])
Pre = dict(zip(r, Pre_arr))
Al3x
  • 31
  • 4

2 Answers2

3

Lists are mutable, so not hashable.

I would recommend using Tuples which are immutable and so can be hashable if it contains immutable elements.

See: List unhashable, but tuple hashable?

Jon
  • 1,820
  • 2
  • 19
  • 43
2

A dictionary key must be immutable (https://realpython.com/lessons/restrictions-dictionary-keys-and-values/), and a list is a mutable object.

In the for loop, you can append tuples instead of lists, as they're immutable

for j in range(0, len(w), 2):
l2 = list((w[j], w[j+1]))
for i in psu:
    if w[j] == i or w[j+1] == i:
        pass
    else:
        m = ('_'.join(l2))
        r.append((m, i))
Pre = dict(zip(r, Pre_arr))
lumalot
  • 141
  • 10