更新时间:2023-11-25 23:31:52
dict.get
可以返回默认值(例如, None
).如果我们以您的示例为例:
dict.get
can return a default value (for example, None
). If we take your examples:
dict_1 = {'A':4, 'C':5}
dict_2 = {'A':1, 'B':2, 'C':3}
dict_3 = {'B':6}
my_keys= ['A','B','C']
然后 dict_1.get('B',None)
是确保我们获得默认 None
值的方法.我们可以以相同的方式遍历所有键:
Then dict_1.get('B', None)
is the way to make sure we get a default None
value. We can loop across all keys the same way:
def dict_to_list(d, keys):
return [d.get(key, None) for key in keys]
示例:
>>> dict_to_list(dict_1, my_keys)
[4, None, 5]
>>> dict_to_list(dict_2, my_keys)
[1, 2, 3]
>>> dict_to_list(dict_3, my_keys)
[None, 6, None]
无
是默认参数,即使未明确指定,因此 dict_1.get('B')
与 dict_1一样有效.get('B',None)
None
is the default argument even if it's not explicitly specified, so dict_1.get('B')
would work just as well as dict_1.get('B', None)