如果字典中缺少键,则插入 NaN

Insert NaN if key is missing in dictionary

我有两本词典

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

对于丢失的键,我希望 ship_list 显示 NaN 喜欢:

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

感谢您的帮助!!!

只需使用 dict.get() 函数即可完成此任务。 Documentation here.

示例:

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

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

输出:

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

备注:

如果您更喜欢 'proper' nan 值,它是 float 数据类型,可用于 Noneisnull()-像验证一样,将 'NaN' 替换为 float('nan').