辞書にループし、辞書値にアクセスしてリストに追加しています。私は辞書数百人をループしています辞書の値にアクセスするときに、特定のキーに値が存在しない場合、NaNを代入する方法はありますか?
example_dict = {"first":241, "second": 5234, "third": "Stevenson", "fourth":3.141592...}
first_list = []
second_list = []
third_list = []
fourth_list = []
...
first_list.append(example_dict["first"]) # append the value for key "first"
second_list.append(example_dict["second"]) # append the value for key "second"
third_list.append(example_dict["third"]) # append the value for key "third"
fourth_list.append(example_dict["fourth"]) # append the value for key "fourth"
:
は、一例として1つの辞書、example_dict
を考えてみましょう。いくつかのキーに値がない可能性があります。この場合、リストにNaN
が追加されます。スクリプトを実行した後、各リストの要素数は同じになります。
new_dict = {"first":897, "second": '', "third": "Duchamps", ...}
の場合、second_list.append(new_dict["second"])
は、NaN
を付加します。
これを行うためのチェックにはどのように書き込まれますか? ifステートメント?
使用 '.get'方法。 '' NaN''は文字列になります: 'second_list.append(new_dict.get( 'second'、 'NaN'))' –
@MosesKoledoyeあなたは 'float( 'nan')'を使うこともできます。 –
この場合、技術的には値*は*存在します。つまり空文字列です。 – MisterMiyagi