Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element to a list inside nested list - python

I am developing a procedure add_to_index, that takes 3 inputs:

  • an index: [[,[url1,url2,...]],...]
  • a keyword: String
  • a url: String

If the keyword is already in the index, url is added to the list of urls associated with that keyword.

If the keyword is not in the index, a new element is to the index:

[keyword,[url]]

CODE

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0
    for lists in index:
        count += 1
        if(lists[0]==keyword): 
            index[count][1].append(url)

    if(flag ==0):
        index.append([keyword,url])   

#calling the function below

add_to_index(index,'google','http://google.com')
print index

output -> [['google', 'http://google.com']]

add_to_index(index,'computing','http://acm.org')
print index

output -> [['google', 'http://google.com'], ['computing', 'http://acm.org']]

add_to_index(index,'google','http://gmail.com') 
print index

error->

index[count][1].append(url)
AttributeError: 'str' object has no attribute 'append'

Expected output:

 [['google', ['http://google.com', 'http://gmail.com']], 
 ['computing', ['http://acm.org']]]
like image 668
akshaynagpal Avatar asked Oct 20 '22 20:10

akshaynagpal


1 Answers

You have done three mistakes, Firstly you have not used the flag and secondly you are adding the url as a string. And finally as Kaivosuketaja has mentioned in the comment, count should be incremented in the end. It can be done otherwise as

index = []

def add_to_index(index,keyword,url):
    flag = 0
    count = 0

    for lists in index:

        if(lists[0]==keyword): 
            flag = 1
            index[count][1].append(url)
        count += 1

    if(flag ==0):
        index.append([keyword,[url]])   
        # Take note of append away here
#calling the function below

add_to_index(index,'google','http://google.com')
print index

add_to_index(index,'computing','http://acm.org')
print index

add_to_index(index,'google','http://gmail.com') 
print index

The output now is

[['google', ['http://google.com']]]
[['google', ['http://google.com']], ['computing', ['http://acm.org']]]
[['google', ['http://google.com', 'http://gmail.com']], ['computing', ['http://acm.org']]]
like image 198
Bhargav Rao Avatar answered Oct 22 '22 21:10

Bhargav Rao