rp346
rp346

Reputation: 7028

python update dict in list or append if doesn't exist

I am trying to update existing json file which has list of dict in python3

    .
    .

    "guests": [
        {
            "name": "name1",
            "package": {
                "age": "30",
                "dob": "Oct 10",
                "image": "name1.img",
                "address": "xxx"
            }
        },
        {
            "name": "name2",
            "package": {
                "age": "20",
                "dob": "Oct 10",
                "image": "name2.img",
                "address": "xxx"
            }
        }
    ]

    .
    .

I want to update each guests data with new data, if guest (name) doesn't exists then append guest data to the list as a new guest.

how can I achieve this in python ?

Upvotes: 1

Views: 5068

Answers (3)

Andriy
Andriy

Reputation: 141

To update a json file, firstly you need to load it to a dict. Then you update the dict. Finally, you dump the updated dict back to the json file. Concerning updating the list of guest object, I will rather build a dict of guests with name as key (according to the question description, it is expected that the names are unique) to simplify the updating routing.

import json

# list of new guests
new_guests = [
  {
    "name": "name1",
    "package": {
      "age": "300",
      "dob": "Jan 1",
      "image": "new_name1.img",
      "address": "yyy"
     }
  },
  {
     "name": "name3",
     "package": {
       "age": "40",
       "dob": "Oct 4",
       "image": "name3.img",
       "address": "zzz"
      }
   }
]

# path to your json file
path_to_json = 'path/to/data.json'

# load json to dict
with open(path_to_json) as f:
  data = json.load(f)

# build dict of json guest using name as key
guests = {x['name']: x for x in data['guests']}

# update guests
for g in new_guests:
  guests[g['name']] = g

# update data and dump it to the file
data['guests'] = [guests[name] for name in guests]
with open(path_to_json, 'w') as f:
  json.dump(data, f)

Upvotes: 0

snnguyen
snnguyen

Reputation: 344

You can use the in operator to check if a certain key is in the dictionary.

new_guests = []
for guest in guests:
    if 'name' not in guest:
        # append new information
        new_info = {}
        new_info['name'] = "your_new_name"
        new_info['package'] = {}  # new info
    else:
        # update with new information
        guest['package'].update({})

Upvotes: 3

sjishan
sjishan

Reputation: 3652

data contains your sample data list. data_new is the data that you want to check if it is exist or not. if the name exist then it is updating the data list and setting a flag that it is updated. if it does not exist then the flag it not set so the new data is appended to the list.

data list

data = { "guests": [
        {
            "name": "name1",
            "package": {
                "age": "30",
                "dob": "Oct 10",
                "image": "name1.img",
                "address": "xxx"
            }
        },
        {
            "name": "name2",
            "package": {
                "age": "20",
                "dob": "Oct 10",
                "image": "name2.img",
                "address": "xxx"
            }
        }
    ] }

query data

guest_new = {
            "name": "name3",
            "package": {
                "age": "21",
                "dob": "Nov 11",
                "image": "name3.img",
                "address": "xxxxxxxxxx"
            }
        }
guest_flag = 0

update if exist or append

for i in range (0, len(data["guests"])):
  if(data['guests'][i]['name'] == guest_new['name']):
    data['guests'][i]['package'] = guest_new['package']
    guest_flag = 1

if(guest_flag == 0):    
  data['guests'].append(guest_new)

Upvotes: 2

Related Questions