1

I wanna remove a dictionary from a nested dictionary and I don't know how. From this dictionary:

dict = {  
    'user': [
        {
            'firstName': 'john',
            'lastName': 'doe',
            'movieList': []
        },
        {
            'firstName': 'sarah',
            'lastName': 'doe',
            'movieList': []
        },
        {
            'firstName': 'john',
            'lastName': 'smith',
            'movieList': []
        },
        {
            'firstName': 'sarah',
            'lastName': 'smith',
            'movieList': []
        }
    ], 'movie': []
}

I want to remove:

{
    'firstName': 'john', 
    'lastName': 'doe', 
    'movieList': []
}

which has the index 0 I tried using delete but i get this error:

dict['user'][userId] TypeError: list indices must be integers or slices, not str
Elis Byberi
  • 1,422
  • 1
  • 11
  • 20
Gallo
  • 175
  • 1
  • 2
  • 11

4 Answers4

2

First, I wouldn't name the dict "dict", use "d" or something else.

dict['user'].pop(0)
SuperStew
  • 2,857
  • 2
  • 15
  • 27
0

I would write a comment, but my reputation is too low. It seems like your variable userId might be a string instead of an integer. If this is the case, try converting userId to an int:

userId = int(userId)
0

See this question for more info on del pop and remove Difference between del, remove and pop on lists

If you do not want to use the dictionary you are removing, I would use del, as below:

d = {'user': [{'firstName': 'john', 'lastName': 'doe', 'movieList': []},
              {'firstName': 'sarah', 'lastName': 'doe', 'movieList': []},
              {'firstName': 'john', 'lastName': 'smith', 'movieList': []},
              {'firstName': 'sarah', 'lastName': 'smith', 'movieList': []}], 'movie': []}

del d['user'][0]

This [0] is deleting the first index of the list stored as the value of the 'user' key

If you are repeatedly deleting the first index of your list and your list is long, consider using a deque() instead, which has fast pops from either end: https://docs.python.org/3/library/collections.html#collections.deque

Also, don't call your variables the same name as their types, aka don't call your dictionary variable dict

ragardner
  • 1,836
  • 5
  • 22
  • 45
0

You can try this:

dict1 = {'user': [{'firstName': 'john', 'lastName': 'doe', 'movieList': []}, {'firstName': 'sarah', 'lastName': 'doe', 'movieList': []}, {'firstName': 'john', 'lastName': 'smith', 'movieList': []}, {'firstName': 'sarah', 'lastName': 'smith', 'movieList': []}], 'movie': []}
new_dict = {a:b[1:] if b else b for a, b in dict1.items()}

Output:

{'movie': [], 'user': [{'lastName': 'doe', 'movieList': [], 'firstName': 'sarah'}, {'lastName': 'smith', 'movieList': [], 'firstName': 'john'}, {'lastName': 'smith', 'movieList': [], 'firstName': 'sarah'}]}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102