When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?
<p>I am looping through dictionaries and accessing the dictionary values to append to a list. </p>

<p>Consider one dictionary as an example, <code>example_dict</code>:</p>

<pre><code>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"
</code></pre>

<p>I am looping through hundreds of dictionaries. It is possible that some keys do not have values. In this case, I would like an <code>NaN</code> appended to the lists---after running the script, each list should have the same number of elements. </p>

<p>If <code>new_dict = {"first":897, "second": '', "third": "Duchamps", ...}</code>, then <code>second_list.append(new_dict["second"])</code> would append <code>NaN</code>. </p>

<p>How does one write in a check for this to occur? An if statement?</p>

<p>You can perform a check for values that are not <code>""</code> and simply do something like this:</p>

<pre><code>second_list.append(new_dict["second"] if new_dict["second"] != "" else "NaN"))
</code></pre>

<p>So, if key <code>second</code> exists in <code>new_dict</code> and is an empty string, then <code>NaN</code> will be appended to <code>second_list</code>. </p>

<p>If you were looking to create a list of values from the dictionary applying the logic above, you can do the following, both are the same, first is expanded, and the second is the shortened comprehension: </p>

<h1>method 1</h1>

<pre><code>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')
</code></pre>

<h1>method 2 (comprehension)</h1>

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

python python-3.x dictionary key-value