2016-10-10 8 views
0

辞書にループし、辞書値にアクセスしてリストに追加しています。私は辞書数百人をループしています辞書の値にアクセスするときに、特定のキーに値が存在しない場合、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ステートメント?

+0

使用 '.get'方法。 '' NaN''は文字列になります: 'second_list.append(new_dict.get( 'second'、 'NaN'))' –

+1

@MosesKoledoyeあなたは 'float( 'nan')'を使うこともできます。 –

+1

この場合、技術的には値*は*存在します。つまり空文字列です。 – MisterMiyagi

答えて

2

あなたは""ではなく、単にこのような何かの値のチェックを実行することができますので、

second_list.append(new_dict["second"] if new_dict["second"] != "" else "NaN")) 

をキーsecondnew_dictに存在し、空の文字列であれば、その後、NaNsecond_listに追加されます。

あなたは上記のロジックを適用した辞書からの値のリストを作成するために探している場合は、次の操作を行うことができ、両方が拡張され、最初に同じであり、第二は短く理解です:

方法1

new_dict = {"first":897, "second": '', "third": "Duchamps"} 
new_list = [] 
for _, v in new_dict.items(): 
    if v != "": 
     new_list.append(v) 
    else: 
     new_list.append('NaN') 

方法2(理解)

new_dict = {"first":897, "second": '', "third": "Duchamps"} 
new_list = [v if v != "" else 'NaN' for _, v in new_dict.items()] 
+0

欠けている値のように見えるのは、空の文字列 '" "'です。その場合、new_dict ["second"]!= "" else "NaN" 'なら' new_dict.get( "second"、 "NaN") 'を' new_dict ["second"]に置き換えてください。リストの理解はより洗練されているかもしれません。 –

+0

@SethDifleyそれを私の注意を喚起してくれてありがとう、私は何とかそれを逃した。私の答えを更新する。 – idjaw

+0

ユーザー@MosesKoledoyeが '.get()'を使って言及しました。これは最短の答えのようです---上記の答えをどうやって保持していますか? – ShanZhengYang

関連する問題