👻 *Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!*

NoteThis forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The `numpy.poly1d()`

function allows to define a polynomial function. It therefore makes it straightforward to use *natural operations* on polynomials.

It is a convenience class, used to encapsulate "natural‚" operations on polynomials so that said operations may take on their customary form in code.

Syntax:numpy.poly1d(arr, root, var)

Parameters :arr :[array_like] The polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.

root :[bool, optional] True means polynomial roots. Default is False.var :variable like x, y, z that we need in polynomial [default is x].

Arguments :

c :Polynomial coefficient.coef :Polynomial coefficient.

coefficients :Polynomial coefficient.order :Order or degree of polynomial.

o :Order or degree of polynomial.r :Polynomial root.

roots :Polynomial root.

Return:Polynomial and the operation applied

## Numpy poly1d Examples

### np.poly1d example #1

def _break_points(num, den): """Extract break points over real axis and gains given these locations""" # type: (np.poly1d, np.poly1d) -> (np.array, np.array) dnum = num.deriv(m=1) dden = den.deriv(m=1) polynom = den * dnum - num * dden real_break_pts = polynom.r # don’t care about infinite break points real_break_pts = real_break_pts[num(real_break_pts) != 0] k_break = -den(real_break_pts) / num(real_break_pts) idx = k_break >= 0 # only positives gains k_break = k_break[idx] real_break_pts = real_break_pts[idx] if len(k_break) == 0: k_break = [0] real_break_pts = den.roots return k_break, real_break_pts

### np.poly1d example #2

def test_poly1d_math(self): # here we use some simple coeffs to make calculations easier p = np.poly1d([1., 2, 4]) q = np.poly1d([4., 2, 1]) assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75]))) assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.])) assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.])) p = np.poly1d([1., 2, 3]) q = np.poly1d([3., 2, 1]) assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.])) assert_equal(p + q, np.poly1d([4., 4., 4.])) assert_equal(p - q, np.poly1d([-2., 0., 2.])) assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.])) assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.])) assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.])) assert_equal(p.deriv(), np.poly1d([2., 2.])) assert_equal(p.deriv(2), np.poly1d([2.])) assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])), (np.poly1d([1., -1.]), np.poly1d([0.])))

### np.poly1d example #3

def test_poly1d_str_and_repr(self): p = np.poly1d([1., 2, 3]) assert_equal(repr(p), ’poly1d([1., 2., 3.])’) assert_equal(str(p), ’ 2 ’ ’1 x + 2 x + 3’) q = np.poly1d([3., 2, 1]) assert_equal(repr(q), ’poly1d([3., 2., 1.])’) assert_equal(str(q), ’ 2 ’ ’3 x + 2 x + 1’) r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j]) assert_equal(str(r), ’ 3 2 ’ ’(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)’) assert_equal(str(np.poly1d([-3, -2, -1])), ’ 2 ’ ’-3 x - 2 x - 1’)

### np.poly1d example #4

def data_analysis(e_ph, flux, method="least"): if method == "least": coeffs = np.polyfit(x=e_ph, y=flux, deg=11) polynom = np.poly1d(coeffs) x = np.linspace(e_ph[0], e_ph[-1], num=100) pd = np.polyder(polynom, m=1) indx = np.argmax(np.abs(pd(x))) eph_c = x[indx] pd2 = np.polyder(polynom, m=2) p2_roots = np.roots(pd2) p2_roots = p2_roots[p2_roots[:].imag == 0] p2_roots = np.real(p2_roots) Eph_fin = find_nearest(p2_roots,eph_c) return Eph_fin, polynom elif method == "new method": pass #plt.plot(Etotal, total, "ro") #plt.plot(x, polynom(x))

### np.poly1d example #5

def _systopoly1d(sys): """Extract numerator and denominator polynomails for a system""" # Allow inputs from the signal processing toolbox if (isinstance(sys, scipy.signal.lti)): nump = sys.num denp = sys.den else: # Convert to a transfer function, if needed sys = _convert_to_transfer_function(sys) # Make sure we have a SISO system if (sys.inputs > 1 or sys.outputs > 1): raise ControlMIMONotImplemented() # Start by extracting the numerator and denominator from system object nump = sys.num[0][0] denp = sys.den[0][0] # Check to see if num, den are already polynomials; otherwise convert if (not isinstance(nump, poly1d)): nump = poly1d(nump) if (not isinstance(denp, poly1d)): denp = poly1d(denp) return (nump, denp)

### np.poly1d example #6

def quadraticInterpolation(valueList2d, numDegrees, n, startTime=None, endTime=None): ’’’ Generates a series of points on a smooth curve that cross the given points numDegrees - the degrees of the fitted polynomial - the curve gets weird if this value is too high for the input n - number of points to output startTime/endTime/n - n points will be generated at evenly spaced intervals between startTime and endTime ’’’ _numpyCheck() x, y = zip(*valueList2d) if startTime is None: startTime = x[0] if endTime is None: endTime = x[-1] polyFunc = np.poly1d(np.polyfit(x, y, numDegrees)) newX = np.linspace(startTime, endTime, n) retList = [(n, polyFunc(n)) for n in newX] return retList

### np.poly1d example #7

def fit_y(self, X, Y, x1, x2): len(X) != 0 # if X only include one point, the function will get line y=Y[0] if np.sum(X == X[0]) == len(X): return Y[0], Y[0] p = np.poly1d(np.polyfit(X, Y, 1)) return p(x1), p(x2)

### np.poly1d example #8

def remove_linear_BG_XAS_preedge( xmcd_data, scanparams, process_parameters=None, process_number=-1 ): """Should remove a linear bg based on the preedge average""" preedge_spectrum = get_preedge_spectrum(process_parameters, xmcd_data) preedge_poly = np.poly1d( np.polyfit(preedge_spectrum["Energy"], preedge_spectrum["XAS"], 1) ) xas_bg = preedge_poly(xmcd_data["Energy"]) for xas in ["XAS+", "XAS-", "XAS"]: xmcd_data[xas] -= xas_bg return (xmcd_data, {"xas_bg_poly_coeffs": " ".join(map(str, preedge_poly.coeffs))})

### np.poly1d example #9

def fit_y(self, X, Y, x1, x2): len(X) != 0 # if X only include one point, the function will get line y=Y[0] if np.sum(X == X[0]) == len(X): return Y[0], Y[0] p = np.poly1d(np.polyfit(X, Y, 1)) return p(x1), p(x2)

### np.poly1d example #10

def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None, limits=None, monic=0,eval_func=None): np.poly1d.__init__(self, roots, r=1) equiv_weights = [weights[k] / wfunc(roots[k]) for k in range(len(roots))] self.__dict__[’weights’] = np.array(list(zip(roots,weights,equiv_weights))) self.__dict__[’weight_func’] = wfunc self.__dict__[’limits’] = limits mu = sqrt(hn) if monic: evf = eval_func if evf: eval_func = lambda x: evf(x)/kn mu = mu / abs(kn) kn = 1.0 self.__dict__[’normcoef’] = mu self.__dict__[’coeffs’] *= kn # Note: eval_func will be discarded on arithmetic self.__dict__[’_eval_func’] = eval_func

👻 *Read also: what is the best laptop for engineering students?*

## numpy.poly1d () in Python __dict__: Questions

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

5 answers

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The `update()`

method would be what I need, if it returned its result instead of modifying a dictionary in-place.

```
>>> x = {"a": 1, "b": 2}
>>> y = {"b": 10, "c": 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{"a": 1, "b": 10, "c": 11}
```

How can I get that final merged dictionary in `z`

, not `x`

?

(To be extra-clear, the last-one-wins conflict-handling of `dict.update()`

is what I"m looking for as well.)

Answer #1

## How can I merge two Python dictionaries in a single expression?

For dictionaries `x`

and `y`

, `z`

becomes a shallowly-merged dictionary with values from `y`

replacing those from `x`

.

In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

`z = x | y # NOTE: 3.9+ ONLY`

In Python 3.5 or greater:

`z = {**x, **y}`

In Python 2, (or 3.4 or lower) write a function:

`def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z`

and now:

`z = merge_two_dicts(x, y)`

### Explanation

Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:

```
x = {"a": 1, "b": 2}
y = {"b": 3, "c": 4}
```

The desired result is to get a new dictionary (`z`

) with the values merged, and the second dictionary"s values overwriting those from the first.

```
>>> z
{"a": 1, "b": 3, "c": 4}
```

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

```
z = {**x, **y}
```

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

```
z = {**x, "foo": 1, "bar": 2, **y}
```

and now:

```
>>> z
{"a": 1, "b": 3, "foo": 1, "bar": 2, "c": 4}
```

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What"s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

```
z = x.copy()
z.update(y) # which returns None since it mutates z
```

In both approaches, `y`

will come second and its values will replace `x`

"s values, thus `b`

will point to `3`

in our final result.

## Not yet on Python 3.5, but want a *single expression*

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a *single expression*, the most performant while the correct approach is to put it in a function:

```
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
```

and then you have a single expression:

```
z = merge_two_dicts(x, y)
```

You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:

```
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
```

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries `a`

to `g`

:

```
z = merge_dicts(a, b, c, d, e, f, g)
```

and key-value pairs in `g`

will take precedence over dictionaries `a`

to `f`

, and so on.

## Critiques of Other Answers

Don"t use what you see in the formerly accepted answer:

```
z = dict(x.items() + y.items())
```

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. **In Python 3, this will fail** because you"re adding two `dict_items`

objects together, not two lists -

```
>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: "dict_items" and "dict_items"
```

and you would have to explicitly create them as lists, e.g. `z = dict(list(x.items()) + list(y.items()))`

. This is a waste of resources and computation power.

Similarly, taking the union of `items()`

in Python 3 (`viewitems()`

in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, **since sets are semantically unordered, the behavior is undefined in regards to precedence. So don"t do this:**

```
>>> c = dict(a.items() | b.items())
```

This example demonstrates what happens when values are unhashable:

```
>>> x = {"a": []}
>>> y = {"b": []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: "list"
```

Here"s an example where `y`

should have precedence, but instead the value from `x`

is retained due to the arbitrary order of sets:

```
>>> x = {"a": 2}
>>> y = {"a": 1}
>>> dict(x.items() | y.items())
{"a": 2}
```

Another hack you should not use:

```
z = dict(x, **y)
```

This uses the `dict`

constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it"s difficult to read, it"s not the intended usage, and so it is not Pythonic.

Here"s an example of the usage being remediated in django.

Dictionaries are intended to take hashable keys (e.g. `frozenset`

s or tuples), but **this method fails in Python 3 when keys are not strings.**

```
>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
```

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for `dict(**y)`

is for creating dictionaries for readability purposes, e.g.:

```
dict(a=1, b=10, c=11)
```

instead of

```
{"a": 1, "b": 10, "c": 11}
```

## Response to comments

Despite what Guido says,

`dict(x, **y)`

is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.

Again, it doesn"t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. `dict`

broke this consistency in Python 2:

```
>>> foo(**{("a", "b"): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{("a", "b"): None})
{("a", "b"): None}
```

This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

More comments:

`dict(x.items() + y.items())`

is still the most readable solution for Python 2. Readability counts.

My response: `merge_two_dicts(x, y)`

actually seems much clearer to me, if we"re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

`{**x, **y}`

does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.

Yes. I must refer you back to the question, which is asking for a *shallow* merge of * two* dictionaries, with the first"s values being overwritten by the second"s - in a single expression.

Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:

```
from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
```

Usage:

```
>>> x = {"a":{1:{}}, "b": {2:{}}}
>>> y = {"b":{10:{}}, "c": {11:{}}}
>>> dict_of_dicts_merge(x, y)
{"b": {2: {}, 10: {}}, "a": {1: {}}, "c": {11: {}}}
```

Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".

## Less Performant But Correct Ad-hocs

These approaches are less performant, but they will provide correct behavior.
They will be *much less* performant than `copy`

and `update`

or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they *do* respect the order of precedence (latter dictionaries have precedence)

You can also chain the dictionaries manually inside a dict comprehension:

```
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
```

or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

```
dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
```

`itertools.chain`

will chain the iterators over the key-value pairs in the correct order:

```
from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
```

## Performance Analysis

I"m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)

```
from timeit import repeat
from itertools import chain
x = dict.fromkeys("abcdefg")
y = dict.fromkeys("efghijk")
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
```

In Python 3.8.1, NixOS:

```
>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
```

```
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
```

## Resources on Dictionaries

- My explanation of Python"s
**dictionary implementation**, updated for 3.6. - Answer on how to add new keys to a dictionary
- Mapping two lists into a dictionary
- The official Python docs on dictionaries
- The Dictionary Even Mightier - talk by Brandon Rhodes at Pycon 2017
- Modern Python Dictionaries, A Confluence of Great Ideas - talk by Raymond Hettinger at Pycon 2017

Answer #2

In your case, what you can do is:

```
z = dict(list(x.items()) + list(y.items()))
```

This will, as you want it, put the final dict in `z`

, and make the value for key `b`

be properly overridden by the second (`y`

) dict"s value:

```
>>> x = {"a":1, "b": 2}
>>> y = {"b":10, "c": 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{"a": 1, "c": 11, "b": 10}
```

If you use Python 2, you can even remove the `list()`

calls. To create z:

```
>>> z = dict(x.items() + y.items())
>>> z
{"a": 1, "c": 11, "b": 10}
```

If you use Python version 3.9.0a4 or greater, then you can directly use:

```
x = {"a":1, "b": 2}
y = {"b":10, "c": 11}
z = x | y
print(z)
```

```
{"a": 1, "c": 11, "b": 10}
```

Answer #3

An alternative:

```
z = x.copy()
z.update(y)
```

How do I copy a string to the clipboard?

2 answers

I"m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python?

Answer #1

Actually, `pywin32`

and `ctypes`

seem to be an overkill for this simple task. `Tkinter`

is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

If all you need is to put some text to system clipboard, this will do it:

```
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append("i can has clipboardz?")
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
```

And that"s all, no need to mess around with platform-specific third-party libraries.

If you are using Python 3, replace `TKinter`

with `tkinter`

.

Python script to copy text to clipboard

2 answers

I just need a python script that copies text to the clipboard.

After the script gets executed i need the output of the text to be pasted to another source. Is it possible to write a python script that does this job?