Home > front end >  How to loop inside a list that contains a dictionary
How to loop inside a list that contains a dictionary

Time:02-17

I'm trying to loop inside entities list at first, then I want to loop inside chat sources of id=1. After that id=2, then its chat sources 1,2,3. And so on.

This structure can't solve my problem.

entities = [
    {id: 1, "chat_sources": [1, 2, 3]},
    {id: 2, "chat_sources": [1, 2, 3]},
    {id: 3, "chat_sources": [1, 2, 3]}
]

for i in entities:
    for j in entities["chat_sources"]:
        print(j)

CodePudding user response:

You're almost there:

entities = [
    {id: 1, "chat_sources": [1, 2, 3]},
    {id: 2, "chat_sources": [1, 2, 3]},
    {id: 3, "chat_sources": [1, 2, 3]}
]

for entity in entities: # entity is already the item rather than its index
    for j in entity["chat_sources"]: # note it's entity, not entities
        print(j)

CodePudding user response:

for elem in entities:
    print(*elem['chat_sources'], sep='\n') 
  • Related