user2242660
user2242660

Reputation: 35

Iterate through a Python Dictionary and delete a particular element if matches a specific string

I have a dictionary like-

mydict = {
  'users': [
    {
      'userid': 'u1234',
      'name': 'user1'
    },
    {
      'userid': 'u0007',
      'name': 'user2'
    }
  ]
}

I want a functionality such that if I pass userid=u1234 it should iterate through the dictionary and delete the details for that userid from the dictionary and then write the output to a file.

Upvotes: 0

Views: 58

Answers (3)

Adam Smooch
Adam Smooch

Reputation: 1322

I'd simplify:

user_list = myDict['users']
for usr_dict in user_list:
  if usr_dict['name'] = name_to_remove:
    myDict['users'].remove(usr_dict)

Also, zooming out one step to improve lookup efficiency (and loop simplicity), you could [re-]structure your myDict as so:

users_dict = {
       'u1234': {
              'userid': 'u1234'
              'name': 'user1'
        },
        'u0007': {
              'userid': 'u0007'
              'name': 'user2'
        }
}

then your loop could become:

for uid, obj in users_dict.items():
  if obj['name'] == username_to_delete:
    users_dict.remove(uid)

Upvotes: 1

Jacob
Jacob

Reputation: 1840

This code will handle your request of deleting a specific user:

for user in mydict['users']:
    if user['userid'] == 'u1234':
        mydict['users'].remove(user)

Upvotes: 1

Muhammad Adeel
Muhammad Adeel

Reputation: 175

Try the following code:-

for i,v in mydict.items():
    for a in v:
        if (a['userid'] == 'u1234'):
            v.remove(a)

Then use following code to write to a file:-

import json
with open('result.json', 'w') as fp:
    json.dump(mydict, fp)

Upvotes: 2

Related Questions