あなたは値を取得するdict.get('key', default=None)
を使用することができます
このようなauthors.jsonファイルと仮定:あなたは
[
{
"author": "Mark Twain"
},
{
"authorFirstName": "Mark",
"authorLastName": "Twain"
},
{
"noauthor": "error"
}
]
をすることができます以下を使用してください
import json
people = json.load(open("authors.json"))
for person in people:
author = person.get('author')
# If there is no author key then author will be None
if not author:
# Try to get the first name and last name
fname, lname = person.get('authorFirstName'), person.get('authorLastName')
# If both first name and last name keys were present, then combine the data into a single author name
if fname and lname:
author = "{} {}".format(fname, lname)
# Now we either have an author because the author key existed, or we built it from the first and last names.
if author is not None:
print("Author is {}".format(author))
else:
print("{} does not have an author".format(person))
OUTPUT
Author is Mark Twain
Author is Mark Twain
{u'noauthor': u'error'} does not have an author
はあなたの要件に応じて、 '作者がNoneの場合:'より適切かもしれません。これは、 'author'が' False'(JSONでは 'false')、' '"、 '0'、または' 0.00'であればエラーを表示します。あるいは '[]'や '{} 'でも可能です。そして、私は 'null'(これはもちろんPythonでは' None'に出てきます)と思います。 –
フェアポイント@WayneWernerが更新されました。 – sberry