Search code examples
pythonjupyter-notebookampl

Convert type instance to dictionary


I have an instance that I get as a result of iAMPL jupyter notebook magic. How can I convert that to a dictionary in python?

print(x)

Returns the following output:

{('87', '41'): 0.0, ('59', '20'): 0.0, ('32', '40'): 0.0, ('49', '2'): 0.0, ('1', '20'): 0.0, ('21', '17'): 0.0, ('92', '3'): 0.0, ('55', '30'): 0.0, ('3', '15'): 0.0, ('8', '51'): 0.0, ('24', '28'): 0.0, ('18', '44'): 0.0, ('82', '38'): 0.0, ('63', '47'): 0.0, ('102', '47'): 0.0, ('87', '11'): 0.0, ('79', '14'): 0.0, ('4', '30'): 0.0, ('63', '6'): 0.0, ('71', '10'): 0.0, ('11', '33'): 0.0, ('54', '50'): 0.0, ('25', '13'): 0.0, ('47', '24'): 0.0, ('77', '1'): 1.0, ('3', '27'): 0.0, ('73', '7'): 0.0, ('63', '17'): 0.0, ('45', '21'): 0.0, ('16', '22'): 0.0, ('23', '29'): 0.0, ('7', '1'): 0.0, ('51', '2'): 0.0, ('83', '47'): 0.0, ('65', '51'): 0.0

Solution

  • Ok, I'm try a pragmatic approach since all attempts to find the exact type of this has failed.

    Printing x seems to print a valid python dictionary in a string form, so what I propose (which may not be optimal) is to use x converted as str and feed it to ast.literal_eval, like this:

    import ast
    
    d = ast.literal_eval(str(x))
    

    d is now a valid python dictionary:

    print(d[('87','41')])
    

    returns 0.0

    maybe there's a more elegant solution, but that does the job in the meanwhile.