The Python Oracle

Sympy solve returns strange dictionary, when it should not return any

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay

--

Chapters
00:00 Question
02:37 Accepted answer (Score 2)
04:18 Thank you

--

Full question
https://stackoverflow.com/questions/7022...

Question links:
[Python Sympy solve returns list vs. dictionary]: https://stackoverflow.com/questions/6595...
[Are quoted dictionary keys an absolute must?]: https://stackoverflow.com/questions/2679...

Accepted answer links:
https://docs.sympy.org/latest/modules/so...
https://github.com/sympy/sympy/blob/mast...
https://github.com/sympy/sympy/blob/mast...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #dictionary #sympy

#avk47



ACCEPTED ANSWER

Score 4


You can't access via dict_min[x] or dict_min["x"] because x is of type sympy.core.symbol.Symbol. The keys of this dict are of type sympy.core.symbol.Symbol.

dict_min[x] does not work because no x variable is defined in your code.

dict_min["x"] does not work because here you define x as a string, but the key named x in dict_min is of type sympy.core.symbol.Symbol.

There is no problem with your class.

However, you can do this:

dict_min[funz.x]

or:

x = funz.x
dict_min[x]

So, dict_min is not a strange dict type from sympy, that's a classic Python dict which keys are of type sympy.core.symbol.Symbol. The keys are the symbols of your equation. Perhaps it was confusing because your symbols x and y were defined in your class and via sym.symbols('x y').

If you want to ALWAYS get a list:

In minim, you should set dict=True instead of False. By doing this, you will "always get a list of solution mappings" (https://docs.sympy.org/latest/modules/solvers/solvers.html). Yes, the goal of dict=True is to ensure that the returned variable will be of type list . I agree that could seems a bit strange.

Some informations about this flag from the source code of solve(): https://github.com/sympy/sympy/blob/master/sympy/solvers/solvers.py#L406

And here is the effect of the flag is_dict: https://github.com/sympy/sympy/blob/master/sympy/solvers/solvers.py#L1249

As for sympy 1.9.