1

How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

room_msg =  [
 {
  'msgID': 1, 
  'username': 'User1',
  'msg': 'msg1', 
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2', 
  'msg': 'msg2', 
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3, 
  'username': 'User3', 
  'msg': 'msg3', 
  'time_stamp': 'May-31 05:29PM'} ]

Like if I select 'msgID': 3 after deleting the 'msgID': 3 the array should like this

room_msg = [
 {
  'msgID': 1, 
  'username': 'User1',
  'msg': 'msg1', 
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2', 
  'msg': 'msg2', 
  'time_stamp': 'May-31 05:29PM'}
]

Is that possible? I can't find x with that msgID room_msg[x].

snatchysquid
  • 1,283
  • 9
  • 24
Najmus Sakib
  • 447
  • 5
  • 14
  • FWIW: Python has lists as the basic sequence collection type, not arrays; [..] creates a list. There are many examples on how to manipulate lists - now using the right terminology, try some internet/SO searches. “python remove list item by property” (eg.) – user2864740 May 31 '20 at 21:51
  • any code you have tried to solve this problem. – sahasrara62 May 31 '20 at 21:51
  • Does this answer your question? [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value) – sahasrara62 May 31 '20 at 22:07

5 Answers5

1

You can use list comprehension:

room_msg = [m for m in room_msg if m['msgID'] != 3]

from pprint import pprint
pprint(room_msg)

Prints:

[{'msg': 'msg1',
  'msgID': 1,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User1'},
 {'msg': 'msg2',
  'msgID': 2,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User2'}]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

This simple code should do it:

desired_id = 3  # example id

for i, msg in enumerate(room_msg):
    if msg['msgID'] == desired_id:
        del room_msg[i]
snatchysquid
  • 1,283
  • 9
  • 24
0

Try using del on the matching array indices.

for index, msg in enumerate(room_msg):
    if msg['msgID'] == 3:
        del room_msg[index]
Heitor Chang
  • 6,038
  • 2
  • 45
  • 65
0

This could be a way - or you use the msgID as Ident for nested - than you can erase with del room_msg[msg]

def search_and_delete(msg):
    count = 0
    for x in room_msg:
        if x['msgID'] == msg:
            room_msg.pop(count)
        count+=1
Sonikk
  • 39
  • 5
0

To delete a object from an array in python use

del arr["index"]
Damnik Jain
  • 374
  • 2
  • 11