I have a list named attributes which contains all possible fields. Like this:
attributes = [
'name',
'phone_no',
'address',
'hobby',
]
I also have some dictionaries which have some key-value pairs, and the keys are always a subset of the attributes list. One such dictionary is:
my_dict = {'name': "Kanchon Gharami", 'address': "Bangladesh"}
Here in this dictionary only two keys (name & address) are present, rest of the two fields(phone_no & hobby) from the attribute list are not present.
I need to convert it in such a way that it holds all the possible fields as a key and value NAN if no value is given; something like this:
my_dict = {'name': "Kanchon Gharami", 'phone_no' : "NAN", 'address': "Bangladesh", 'hobby' : "NAN"}
Please advise me how to do this with Python?
>Solution :
I suggest you use defaultdict.
Otherwise, you can just loop over your attributes list and add them as keys to your dict.