I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case:
I want to build dictionary A from dict
Though the accepted answer's emphasize on "look before you leap" principle might apply to most languages, more pythonic might be the first approach, based on the python principles. Not to mention it is a legitimate coding style in python. Important thing is to make sure you are using the try except block in the right context and is following best practices. Eg. doing too many things in a try block, catching a very broad exception, or worse- the bare except clause etc.
Easier to ask for forgiveness than permission. (EAFP)
See the python docs reference here.
Also, this blog from Brett, one of the core devs, touches most of this in brief.
See another SO discussion here:
I think the general rule here is will A["blah"]
normally exist, if so try-except is good if not then use if "blah" in b:
I think "try" is cheap in time but "except" is more expensive.
From what I understand, you want to update dict A with key,value pairs from dict B
update
is a better choice.
A.update(B)
Example:
>>> A = {'a':1, 'b': 2, 'c':3}
>>> B = {'d': 2, 'b':5, 'c': 4}
>>> A.update(B)
>>> A
{'a': 1, 'c': 4, 'b': 5, 'd': 2}
>>>
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can capture the condition value dictB.get('hello', None)
in a variable value
in order to both check if it's not None
(as dict.get('hello', None)
returns either the associated value or None
) and then use it within the body of the condition:
# dictB = {'hello': 5, 'world': 42}
# dictA = {}
if value := dictB.get('hello', None):
dictA["hello"] = value
# dictA is now {'hello': 5}