0

I have this program that shows articles and I want to add an option to remove articles. The bottom code is the option to either add or edit an already existing articles content. I was wondering if using part of the code to see if a title exists to remove an article from the list. The json list contains of two objects: title and content. So when removing a title I also want to delete its content.

import json
from bottle import route, run, template, request, redirect, static_file, error

@route('/remove')

    articles = read_articles_from_file()

    title = getattr(request.forms, "title")
    
    append_flag = True
    for i, article in enumerate(articles):     #loop through existing articles
        if title == article['title']:          #if title exists in articles                  
@route('/update', method="POST")
def update_article():
    """
    Receives page title and contents from a form, and creates/updates a
    text file for that page.
    """

    title = getattr(request.forms, "title")
    content = getattr(request.forms, "content")

    articles = read_articles_from_file()

    append_flag = True
    for i, article in enumerate(articles):      #loop through existing articles
        if title == article['title']:           #if new title already exists
            articles[i]['content'] = content    #update articles content
            append_flag = False                 #update flag to false
            break                               #if title is unique, break loop 

    if append_flag:                             #add new post
        articles.append({
            "title": title.strip(),              
            "content": content
        })


    my_file = open("storage/articles.json", "w")
    my_file.write(json.dumps(articles, indent=3))
    my_file.close()
Sultan
  • 33
  • 6
  • list.pop(index) removes an element from a python list. I think that's all your asking. – user2263572 Jan 15 '21 at 20:04
  • 2
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – SyntaxRules Jan 15 '21 at 20:18

2 Answers2

1

First find the item. Then delete it using list.pop list docs. Like so:

>>> articles = [{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> articles
[{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> title_to_remove = 'one'
>>> matching_index = next(i for i, a in enumerate(articles) if a['title'] == title_to_remove)
>>> matching_index
0
>>> articles.pop(matching_index)
{'title': 'one', 'content': 'content_one'}
>>> articles
[{'title': 'two', 'content': 'content_two'}]
SyntaxRules
  • 2,056
  • 23
  • 32
  • How would this be implemented in the function though? – Sultan Jan 15 '21 at 20:23
  • @Sultan Using the same methods. What I've given you is was created using the [python interpreter](https://docs.python.org/3/tutorial/interpreter.html). I'll leave it to you to modify the lines above into a function. – SyntaxRules Jan 15 '21 at 20:26
0

If I wanted to delete an item or items from a list I would go with filtering the list like so:

def remove_article():
    title = 'title_1'  # dummy title to remove
    # dummy articles
    articles = [
        {'title': 'title_1', 'content': 'content_1'},
        {'title': 'title_2', 'content': 'content_2'}
    ]

    articles = list(filter(lambda article: article['title'] != title, articles))

However as I see it, it would be beneficial to just leave the list, and use a dictionary instead. In both of your cases you would like to search an item based on a title.

So why not just make your title as the key of your search?

Same methods with dictionaries (you should be able to convert these to json, too).

def remove_article():
    title = 'title_1'  # dummy title
    # dummy articles
    articles = {
        'title_1': 'content_1',
        'title_2': 'content_2'
    }

    if title in articles:
        del articles[title]


def update_article():
    title = 'title_1'  # dummy title
    content = 'content_1_new'  # dummy content
    articles = {
        'title_1': 'content_1',
        'title_2': 'content_2'
    }

    articles[title] = content

skyzip
  • 237
  • 2
  • 11