'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.

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 1:[1]

I suggest you use defaultdict.

Otherwise, you can just loop over your attributes list and add them as keys to your dict.

Solution 2:[2]

have a base dict and then update the fields that you have in your my_dict

attributes = [
    'name',
    'phone_no',
    'address',
    'hobby',
]

my_dict = {'name': "Kanchon Gharami", 'address': "Bangladesh"}
attributes_tpl = [('name', "NaN"), ('phone_no', "NaN"), ('address', "NaN"), ('hobby', "NaN")]
base_dict = dict(attributes_tpl)
base_dict.update(my_dict)
print(base_dict)

Solution 3:[3]

Here is a small example I’m going to cook up for you, tell me if I’ve misinterpreted the question.

myAttributes = [“name”, “phone”, “address”, “hobby”]
myDict = {“name”: “Kanchon”, “address”: “myHouse”}
newDict = dict()
for item in myAttributes:
   for key, value in myDict.items():
       if key == item:
          newDict[key] = value
          continue
       newDict[key] = None

I’m afraid I can’t test this but I would love to hear if it works.

Solution 4:[4]

attributes = [
    'name',
    'phone_no',
    'address',
    'hobby',
]
my_dict = {'name': "Kanchon Gharami", 'phone_no' : "NAN", 'address': "Bangladesh", 'hobby' : "NAN"}

mydict=dict()

for l in attributes:
    if l=='phone_no':
        mydict[l]="NAN"
    else:
        mydict[l]="test"
print(mydict)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code-Apprentice
Solution 2
Solution 3 Dharman
Solution 4 Fikret Basgul