Reputation: 24930
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.
Assume a number of dictionaries of varying lengths:
dict_1 = {'A':4, 'C':5}
dict_2 = {'A':1, 'B':2, 'C':3}
dict_3 = {'B':6}
The common denominator for these dictionaries is that they all share the keys on this list:
my_keys= ['A','B','C']
but some are missing one or more of the keys.
The intent is to create a list of lists, where each list element is a list of all the existing values in each dictionary, or 'None' where a specific key isn't present. They keys themselves, being identical across all dictionaries, can be disregarded.
So in this case, the expected output is:
final_list =
[[4,"None",5],
[1,2,3],
["None",6,"None"]]
I'm not sure exactly how to approach it. You could start with each element in my_keys
, and check its presence against each key in each dictionary; if the relevant dict has the key, the value of that key is appended to a temporary list; otherwise, 'None' is appended. Once the my_keys
are all iterated over, the temp list is appended to a final list and the cycle start again.
To me at least, it's easier said than done. I tried quite a few things (which I won't bother to post because they didn't get even close). So I was wondering if there is an elegant approach to the problem.
Upvotes: 1
Views: 61
Reputation: 11932
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:
def dict_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)
Upvotes: 2