Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python dictionary operation to add all possible fields

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading