I have a dictionary of dictionaries as follows:
dictofdict = {'001': {'date': 201504, 'status':'New'}, '002': {'date':201504, 'status':'Constant', 'rate':'-10'}, '003':{'date': 201504, 'status':'In Review'}}
The inner dictionaries may or may not have all the following keys: date, status and rate. For example: 001 and 003 do not have the key rate in their dictionary of values.
How do I read this dictionary of dictionaries such that I have an output as follows. I am interested in only the date and status keys from the inner dictionaries.
201504 001 New
201504 002 Constant
201504 003 In Review
You can use an
if
clause to check if they exist in the inner dictionaryIf you are particular about the order then you will have to use
sorted
as a dictionary otherwise is un-orderedAs Padraic mentions you can use a list comprehension to store these values.
This can be used as
As JonCle mentions below
You can use
set.issubset
in your clause too.This can be used as
One final approach is the EAFP. Called as Easier to ask for forgiveness than permission, you can avoid the
if
clause completely here!The working of this is that we assume that the key is present in the dict. If it is not there, an exception would be raised. Here we choose to ignore that as it is not required for us.
Note:
As you have a dictionary here, you can take advantage of the
format
method here to print the keys of the dictionary (You can see a few examples here) and supply the keys of the dictionary as fields informat
This can be done as