0

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.

user2242660
  • 31
  • 1
  • 2
  • 7
  • Hi @user2242660, here's a relevant discussion about finding dictionary keys using values: https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary – oh_my_lawdy Jul 26 '21 at 13:32

3 Answers3

2

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)
1

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

for user in mydict['users']:
    if user['userid'] == 'u1234':
        mydict['users'].remove(user)
Jacob
  • 964
  • 7
  • 16
1

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)
Adam Smooch
  • 717
  • 8
  • 25