A more robust version is this from here
<https://stackoverflow.com/questions/22955888/how-to-extract-all-coefficients-in-sympy/60552819#60552819>
:
>>> def codict(expr, *x):
... collected = Poly(expr, *x).as_expr()
... return dict(i.as_independent(*x)[::-1] for i in Add.make_args(collected))
...
>>> x, a = symbols("x, a")
>>> y = 3 + x + x**2 + a*x*2
>>> codict(y, x)
{1: 3, x**2: 1, x: 2*a + 1}
>>> codict(y+b*z,x,z)
{1: 3, x**2: 1, z: b, x: 2*a + 1}
On Friday, March 20, 2020 at 2:11:07 PM UTC-5, Chris Smith wrote:
>
> On this SO question
> <https://stackoverflow.com/questions/60547540/how-to-get-coefficients-in-sympy-expression-python>
>
> the following approach was posted:
>
> >>> y = 2*x**3 + a*x**2 + b
>
> >>> d = dict(i.as_independent(x)[::-1] for i in Add.make_args(y)); d
>
> {1: b, x**3: 2, x**2: a}
>
>
> You then can use as a key whichever power of x you are interested in; use
> `d.get(1/x, 0)` to default to 0 if the value is not there.
>
> On Friday, March 20, 2020 at 6:00:56 AM UTC-5, Jisoo Song wrote:
>>
>> I know there is 'coeff' method, which gives the coefficient of specific
>> power of variable: e.g. (3/x + 4*x).coeff(x, -1) giving 3.
>>
>> Then, is there any method to give every coeffecient of powers of x? For
>> example, {-1:3, 1:4} where keys are powers and values are coefficient.
>>
>
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/46986563-8491-4807-8041-5f6f614d471b%40googlegroups.com.