How to use list as key in python dictionary

I want to use a dictionary like below: Example: {[8, 16]: [[1,2,4,8], 8], [16, 24]: [[1,2,3,4,8, 12], 12]}

8 and 16 are two numbers to be entered and I need to build a dictionary as above.

Using setdefault I could create a list of values ​​in a dictionary, but not for keys

Below is my code:

#!/usr/bin/env python
"""
        This Program calculates common factors between two Numbers , which 
        is stored on a list and also greatest common factor is also computed.
        All this is stored in a dictionary
        Example: { '[n1, n2]': [[Commonfac1(n1,n2), Commonfac2(n1,n2)....Commonfacn(n1,n2)],GreatestCommonFactor] }
"""
def Factors(number):
        result = []
        for i in range(1, number+1):
                if (number % i) == 0:
                        result.append(i)

        return result

def Common_Factors(n1, n2):
        result = []
        for element in n1:
                if element in n2:
                        result.append(element)

        return result

def greatest_common_factor(common_factors):
        count = 0
        length = len(common_factors)
        current_largest = common_factors[count]
        for i in common_factors:
                count += 1
                if count <= length -1:
                        if current_largest < common_factors[count]:
                                current_largest = common_factors[count]
        return current_largest


def main():
        n1 = 8
        n2 = 16
        result1 = Factors(n1)
        result2 = Factors(n2)

        CF = Common_Factors(result1, result2)

        GCF = greatest_common_factor(CF)

        dict = {}

        dict.setdefault([n1, n2], []).append(CF)
        print dict

if __name__ == '__main__':
        main()

      

When I run the above program, I get below error:

$ python math74.py 
Traceback (most recent call last):
  File "math74.py", line 58, in <module>
    main()
  File "math74.py", line 54, in main
    dict.setdefault([n1, n2], []).append(CF)
TypeError: unhashable type: 'list'

      

Any hints on how I can achieve the above.

To clarify more: {[8, 16]: [[1,2,4,8], 8], [16, 24]: [[1,2,3,4,8,12], 12]}

8, 16 are two numbers to be entered by the user, 1, 2, 4, 8 are common factors and 8 is the largest common factor.

+3


source to share


2 answers


The list is not what you want, because: 1. The list is fluid. This means that it can change (delete / add / change) its values. For example:

>>> testList = [1,5]
>>> d = {"myList": testL}
>>> d
{'myList': [1, 5]}
>>> testList.append(53)
>>> d
{'myList': [1, 5, 53]}
>>> 

      



As you can see, the list can be changed and the keys must be unique.
For inmutable array types, Python has a tuple. Once you have defined a tuple, it cannot be changed. This means that you can also use it as a key in a directory:

>>> myTuple = (4, 5)
>>> myDict = {myTuple: "here is the value"}
>>> myDict
{(4, 5): 'here is the value'}
>>> myTuple.append(9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

      

+5


source


As mentioned, you most likely want to convert the list to a tuple so that it is hashable.

Another approach, especially useful for some more complex objects, might be to use a pickle library that serializes the objects.



Example:

import pickle

my_list = [8, 16]
my_value = 'some_value'
my_dict = {pickle.dumps(my_list): my_value}

my_dict[pickle.dumps([8, 16])]  # This equals to 'some_value'

      

+2


source







All Articles