Home > Back-end >  Not able to create a dictionary dynamically
Not able to create a dictionary dynamically

Time:04-21

I want to create a dictionary dynamically. i have list of packages and want to create a data as below dynamically

package_list = ['package1','package2','package3']

data={
    "packageMap" : {
        "package1" : [],
        "package2" : [],
        "package3" : []
        }
}

Below is the code I am trying but failed with error dictionary update sequence element #0 has length 1; 2 is required :

data = {
    "packageMap" : {}
} 

dump = json.dumps(data)
json_data  = json.loads(dump)
for package in package_list:
    json_data["packageMap"].update(f"{package} : []")

CodePudding user response:

Your json_data is a python dictionary, update method exposed by dict class requires either a dict or any other iterable with key-value pairs instead, you are giving it a string. Replacing that with the key-value pair works fine.

data = {
    "packageMap" : {}
} 

dump = json.dumps(data)
json_data  = json.loads(dump)
for package in package_list:
    json_data["packageMap"].update({package: []})

Reference:- https://docs.python.org/3/library/stdtypes.html#dict.update

CodePudding user response:

As another method, You can add keys to another dictionary and add it to the json later:

package_list = ['package1','package2','package3']

packageMap = {}

for package in package_list:
    packageMap[package]=[]

data["packageMap"] = packageMap

print(data)

CodePudding user response:

dict.update don't accept str as params. You should check its usage in build-in type: dict

  • Related