Categories
Python Answers

How to merge two dictionaries in a single expression with Python?

Sometimes, we want to merge two dictionaries in a single expression with Python.

In this article, we’ll look at how to merge two dictionaries in a single expression with Python.

How to merge two dictionaries in a single expression with Python?

To merge two dictionaries in a single expression with Python, we can use the ** or | operators.

For instance, we write:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)

Then z is {'a': 1, 'b': 3, 'c': 4}.

** is available since Python 3.5.

We can also use the | operator with Python 3.9 or later.

To use it, we write:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x | y

And we get the same value for z.

Conclusion

To merge two dictionaries in a single expression with Python, we can use the ** or | operators.

Categories
Python Answers

How to check whether a file exists without exceptions with Python?

Sometimes, we want to check whether a file exists without exceptions with Python.

In this article, we’ll look at how to check whether a file exists without exceptions with Python.

How to check whether a file exists without exceptions with Python?

To check whether a file exists without exceptions with Python, we can use the os.path.isFile method.

For instance, we write:

import os.path
fname = './foo.txt'
os.path.isfile(fname) 

fname is a file path string.

If the file doesn’t exist at the fname path, then it returns False.

Conclusion

To check whether a file exists without exceptions with Python, we can use the os.path.isFile method.

Categories
Python Answers

How to add a ternary conditional expression with Python?

Sometimes, we want to add a ternary conditional expression with Python.

In this article, we’ll look at how to add a ternary conditional expression with Python.

How to add a ternary conditional expression with Python?

To add a ternary conditional expression with Python, we can following the following format:

a if condition else b

where a and b are expressions.

For instance, if we have:

'true' if True else 'false'

Then true is returned.

Conclusion

To add a ternary conditional expression with Python, we can following the following format:

a if condition else b