Monday 15 July 2013

mapping dictonary a key with multiple values to json in python -



mapping dictonary a key with multiple values to json in python -

i trying map dictionary 1 key has multiple values python. here got.

import json list =['abe','matt','roscoe'] key="name" nodes={} nodes.setdefault(key,list) ['abe', 'matt', 'roscoe'] json_nodes =json.dumps(nodes) json_nodes '{"name": ["abe", "matt", "roscoe"]}'

but have json file similar [ { "name": "abe" }, { "name": "matt" }, { "name": "roscoe" } ]

any suggestions appreciated. in advance.

you have list of names, this

>>> names = ['abe', 'matt', 'roscoe']

you need iterate names, , create new dictionary on every iteration list of dictionaries, this

>>> json.dumps([{"name": name} name in names]) [{"name": "abe"}, {"name": "matt"}, {"name": "roscoe"}]

here,

[{"name": name} name in names]

is called list comprehension. convenient technique generate new lists. in our case, iterate on names for name in names. on every iteration, name have current name corresponding iteration , create new dictionary {"name": name}.

python json list dictionary

No comments:

Post a Comment