ShanZhengYang
ShanZhengYang

Reputation: 17641

When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?

I am looping through dictionaries and accessing the dictionary values to append to a list.

Consider one dictionary as an example, example_dict:

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"

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

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

How does one write in a check for this to occur? An if statement?

Upvotes: 0

Views: 1615

Answers (1)

idjaw
idjaw

Reputation: 26590

You can perform a check for values that are not "" and simply do something like this:

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

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

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:

method 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')

method 2 (comprehension)

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

Upvotes: 2

Related Questions