Check Dictionary Keys For Presence Of List Elements, Create List Of Values If Present, 'none' Otherwise
Forgive the convoluted title, but I couldn't find a more elegant way to express the problem. The closet question I could locate can be found here, but it doesn't quite get me there
Solution 1:
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']
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:
defdict_to_list(d, keys):
return [d.get(key, None) for key in keys]
Example:
>>> 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]
EDIT: 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)
Post a Comment for "Check Dictionary Keys For Presence Of List Elements, Create List Of Values If Present, 'none' Otherwise"