IANZ
IANZ

Reputation: 21

Insert NaN if key is missing in dictionary

I have two dictionaries

dict = {a:'', b:'', c:'', d:''}
ship_list = {a:'1', c:'2'}

for the missing keys, I expect ship_list shows NaN like:

new_list = {a:'1', b:'NaN', c:'2', d:'NaN'}

Thanks for your help!!!

Upvotes: 1

Views: 753

Answers (1)

s3dev
s3dev

Reputation: 9711

This task can be accomplished simply using the dict.get() function. Documentation here.

Example:

empty = {'a':'', 'b':'', 'c':'', 'd':''}
filled = {'a':'1', 'c':'2'}

result = {k: filled.get(k, 'NaN') for k in empty}

Output:

{'a': '1', 'b': 'NaN', 'c': '2', 'd': 'NaN'}

Notes:

If you'd prefer the 'proper' nan value, which is a float data type and can be used in None and isnull()-like validation, replace the 'NaN' with float('nan').

Upvotes: 1

Related Questions