hafidzaini
hafidzaini

Reputation: 76

update json list from a list

how to update json list / array?

j = '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol", "country": "USD"}]'''
    ff = json.loads(j)
add = {"info":"ok"}
print(ff)

[{'title': 'AIG Index', 'country': 'AUD'}, {'title': 'NFP Payrol', 'country': 'USD'}]

for i in (ff):
  i.update(add)
print(ff)

[{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country': 'USD', 'info': 'ok'}]

how if i want to upate based on array? using zip / enumerate not working for json

add = [{"info":"ok"}, {"info":"not ok"}]

i get error, ValueError: dictionary update sequence element #0 has length 1; 2 is required, how to get result

[{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country': 'USD', 'info': 'not ok'}]

Upvotes: 0

Views: 375

Answers (3)

klaas
klaas

Reputation: 1811

I dont think there is a builtin zip for python dicts. But you could simply use something like this:

>>> add = [{"info":"ok"}, {"info":"not ok"}]
>>> for count,i in enumerate(ff):
...     i.update(add[count])
... 
>>> ff
[{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country': 'USD', 'info': 'not ok'}]
>>> 

Upvotes: 1

Can Sucuoglu
Can Sucuoglu

Reputation: 195

Since your data seems simple, you can open you data using pandas, do whatever operation you need and then use to_json() function to save again.

Here is the example

import pandas as pd
j = '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol",  "country": "USD"}]'''
df1 = pd.read_json(j)
df1['ok'] = ['ok','not ok']
df1.to_json('file.json')

Upvotes: 1

d-k-bo
d-k-bo

Reputation: 662

I think this is what you want to do:

import json

ff = json.loads(
    '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol", "country": "USD"}]''')

add = [{"info": "ok"}, {"info": "not ok"}]

for i, f in enumerate(ff):
    f.update(add[i])

Or you can use list comprehension:

ff = [dict(f, **a) for f, a in zip(ff, add)]

Upvotes: 1

Related Questions