Technopolice
Technopolice

Reputation: 497

Mapping list - list as dictionary in python

Not to be confused with this question in Stackoverflow.

I have a list called a = [2, 3, 4, 1]

I have some function say func(), which is as follows:

def func(a):
    o = []
    n = len(a)
    for i in range(n):
        x=a[:]
        x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
        o.append(x)
    return o

and func(a) produces another list as follows:

[[3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]]

Now I want to map the output list to the list from which it is generated. So, how to generate a dictionary in the following format:

a            : o

key          : value1, value2........last value

[2, 3, 4, 1] : [3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]

Upvotes: 1

Views: 74

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52191

Keys in a dictionary cannot be mutable type. You can have a tuple instead. That is

(2, 3, 4, 1) : [3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]

This can be done as

def func(a):
    o = []
    n = len(a)
    for i in range(n):
        x=a[:]
        x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
        o.append(x)
    return {tuple(a):o}

For example func([2,3,4,1]) will now return

{(2, 3, 4, 1): [[3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]]}

Also note: according to documentation :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

POST COMMENT EDIT

You can access the keys directly usin [] notation.

E.g:

l = [2,3,4,1]
a =  func(l)
print (a[tuple(l)])

This will print the list of values.

Or you can loop through the entire dictionary

for i in a.items():
     for j in i:
          print (j)

This will print

 [3, 2, 4, 1]
 [2, 4, 3, 1] 
 [2, 3, 1, 4]
 [1, 3, 4, 2]

Upvotes: 2

Related Questions