25
loading...
This website collects cookies to deliver better user experience
dict.update
and {**d1, **d2}
.>>> set_x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> set_y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> set_x | set_y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> {**set_x, **set_y} # The same as the above
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
set_x | set_y
is the same thing as {**set_x, **set_y}
. on closer inspection, you may notice that the merge is made based on the dictionary key. This is because the operator calculate the element in the dictionaries as a union of sets.{**d1, **d2}
method will rather return a dict class.>>> from collections import defaultdict
>>> fruits = defaultdict(
lambda: None,
{"cabbage":"60% Vitmain C", "carrot":"5% Vitamin C", "broccoli":"70% Vitamin C"}
)
>>> Veggies = defaultdict(
lambda: None,
{"apple":"7% Vitamin C", "mango":"60% Vitamin D", "orange":"88% Vitamin C"}
)
>>> fruits | veggies
defaultdict(<function <lambda> at 0x000002379439DF70>,
{'cabbage': '60% Vitmain C', 'carrot': '5% Vitamin C', 'broccoli': '70% Vitamin C', 'apple': '7% Vitamin C', 'mango': '60% Vitamin D', 'orange': '88% Vitamin C'})
>>> {**fruits, **veggies}
{'cabbage': '60% Vitmain C', 'carrot': '5% Vitamin C', 'broccoli': '70% Vitamin C', 'apple': '7% Vitamin C', 'mango': '60% Vitamin D', 'orange': '88% Vitamin C'}
|=
operator.>>> ds_libraries = {
... "numpy": "Mathematical functions",
... "Pandas": "Data structure manipulations",
... "Scipy": "Scientifc calculations"
}
>>> ds_libraries |= {"Matplot": "Data visualization"}
>>> ds_libraries
{"numpy": "Mathematical functions", "Pandas": "Data structure manipulations", "Scipy": "Scientifc calculations", "Matplot": "Data visualization"}
>>> #...
>>> # List of tuples
>>> ds_libraries |= [("","")]
>>> ds_libraries
removeprefix()
and removesuffix()
methodsremoveprefix
method. The syntax is str.removeprix(prefix)
.>>> string = "Python 3.9 is cool"
>>> string.removeprefix("Python")
' 3.9 is cool'
str.removesuffix(suffix)
>>> string = "Python 3.9 is cool">>> string.removesuffix("cool")'Python 3.9 is '
>>> string = "Python 3.9 is cool"
>>> string.removesuffix("")
"Python 3.9 is cool"
>>> string.removesuffix("")
"Python 3.9 is cool"
while
loop>>> string = "Laracoco"
>>> string.removesuffix("co")
>>> while string.endswith("co"):
... string.removesuffix("co")
...
>>>
>>> string
"Lara"
list[dict]
or list[float]
to type hint, you'd rather use a corresponding capitalized type from the typing module.from typing import List
def greeting(names: List[str]) -> None:
for name in names:
print("Hi", name)
List
and Dict
corresponding generic type is eliminated. Python now has them built into the language for easy type hinting.def greeting(names: list[str]) -> None:
for name in names:
print("Hi", name)
zoneinfo.ZoneInfo
and passing in country/state [or city]
key. It'll return a description of the time zone as an object.from zoneinfo import ZoneInfo
>>> ZoneInfo("Africa/Lagos")
zoneinfo.ZoneInfo(key='Africa/Lagos')
NOTE
If you get an error as the following:
ModuleNotFoundError: No module named 'tzdata'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python39\lib\zoneinfo\_common.py", line 24, in load_tzdata
raise ZoneInfoNotFoundError(f"No time zone found with key {key}")
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Nigeria/Lagos'
That indicate there's no local IANA time zone database in the machine, hence zoneinfo
is unable to locate it. To solve the error, install the tzdata
, which is a module containing the IANA time zone database.
>>> python pip install -m tzdata
zoneinfo.ZoneInfo
, you can create a timestamp with proper time zone.>>> from datetime import datetime
>>> from zoneinfo import ZoneInfo
>>>
>>> timezone = ZoneInfo("Africa/Lagos")
>>> dt = datetime.now(tz=timezone)
>>> dt
datetime.datetime(2021, 8, 16, 10, 59, 1, 937856, tzinfo=zoneinfo.ZoneInfo(key='Africa/Lagos'))
>>> dt.tzinfo # Show time zone description
zoneinfo.ZoneInfo(key='Africa/Lagos')
>>> dt.tzname() # Show time zone name
'WAT'
>>>
graphlib
into the standard library and it contains the graphlin.TopologicalSorter
class to offer functionality to perform topological sort of graph.graphlib
module, you can perform a topological sort to find the total order of dependencies as a list. For instance, you can represent a package and its dependencies as dictionary.dependencies = {
"package_A": ["depedency_A", "depedency_B"],
"dependency_B": ["dependency_F"],
}
package_A
, and from inspection, Package_A
depends on dependency_A
and depedency_B
. depedency_B
depends on dependency_F
. The actual dependencies of package_A
are depedency_A
and depedency_B
.TopologicalSort
class from graphlib
.>>> from graphlib import TopologicalSorter
>>> #...
>>> ts = TopologicalSorter(dependecies)
>>> list(ts.static_order())
['depedency_A', 'depedency_B', 'dependency_F', 'package_A', 'dependency_B']
depedency_A
should be installed first, followed dependency_B
, then dependency_F
, followed by the package and lastly, dependency_B
.NOTE:
I don't claim to have an extensive(it is rather shallow) knowledge about Topological ordering and dependency resolution. See the following for more: Topological sorting - Wikipedia, Total order - Wikipedia, https://en.wikipedia.org/wiki/Dependency_(disambiguation).
math
module has expanded the math.gcd()
function handle multiple argument and so on.