Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop inside a list that contains a dictionary

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading