Identify repeated strings in a list

Asked

Viewed 96 times

0

I’m making a program where a user will add stories, he will add the theme, the title and the body of the story, and I put all this into dictionaries and added them into a list.

 historias = [{'tema':'Princesas', 'titulo':'A princesa', 'A princesa':'TextoAPrincesa'},
             {'tema':'Super Herois', 'titulo':'Iron Man 2', 'Iron Man 2':'TextoIronMan'},
             {'tema':'Princesas', 'titulo':'A princesinha', 'A princesinha':'TextoAprincesinha'}]

So my problem is this, I would like to identify when the theme has equal values, as for example in the dictionary that there are two themes with the same value "Princesses"then I thought of a solution to add the names of the themes in a list and find out if some value repeats itself.

lista = []
for i in range(len(historias)):
    lista.append(historias[i]['tema'])
print(lista)`

But I’m not able to identify if there are repeated values in this list, I searched and just found solutions to discover repeated integers and not strings. Could someone help?

  • 1

    Related? https://answall.com/questions/216413/identificar-elements-repeaters-em-lista-com-python?rq=1

1 answer

0


What I advise is that before you use the method append(), first check if the theme is already in the list with the operator in, returning True if so, and False, if you’re not.

As the condition to add the theme in the list is not present, just use the operator not, to reverse the outcome of the condition.

lista = list()

for i in range(len(historias)):
    if not historias[i]['tema'] in lista:
        lista.append(historias[i]['tema'])

If the order of the elements doesn’t matter, you can use a set and the method add(), because it does not allow repeated elements. Getting the code like this:

lista = set()

for i in range(len(historias)):
        lista.add(historias[i]['tema'])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.