khushali shah
khushali shah

Reputation: 65

loop through json objects and add to dictionary with same key and append to list

I want to loop through the json object and add the json values to dictionary and finally append that dictionary to list. For example:-

lists=[]
dicts={}
for objects in json:
   dicts["a"]= objects["abc"]
   dicts["b"] = objects["xyz"]
   lists.append(dicts)

Input data json:-

{ "json" : [ { 'abc'= 'string1', 'xyz='string2', 'a': 'name'}, { 'abc'= 'john', 'xyz='joe', 'a': 'name'},{ 'abc'= 'b', 'xyz='c', 'a': 'name'} ]}

Expectation for the output is list inside the dictionary like this:-

[{'a': 'string1','b': 'string2'}, {'a': 'john','b': 'joe'}]

How can i achieve this? Any help much appreciated!

Upvotes: 0

Views: 1784

Answers (1)

Rakesh
Rakesh

Reputation: 82755

Using dicts you are over-writing with the last value in json instead

Use:

results = []
for objects in json:
    results.append({"a": objects["abc"], "b": objects["xyz"]})

Upvotes: 1

Related Questions