Python - Nested lists - Call nested indexes of sublist

I have a list with nested sublists like this:

my_list = {'active': {'type': 'boolean', 'string': 'Active'}, 'name': {'type': 'char', 'string': 'Title'}, 'description': {'type': 'html', 'string': 'Description'}, 'priority': {'type': 'selection', 'string': 'Priority'}, 'product': {'type': 'char', 'help': 'Selected product by user', 'string': 'Product'}}

You can notice that sublists doesn't have always the same content: 'type', 'string' and sometimes 'help'.

I can run a basic for loop to display elements of the list:

for i in my_list:
    print(i)

Which returns to me:

active
name
description
priority
product

But how can I loop through items of the sublists? I think I need to nest an other for loop.

I want to display specifics information like:

- Active: active, boolean
- Title: name, char
- Description: description, html
- Priority: priority, selection
- Product: product, char, Selected product by user

Solution 1:

So first thing first. This is not a list. This is a nested dictionary or dict in Python. Here is a link that shows you the differences: Difference between List and Dictionary in Python

You can refer to a dict element via it's key name. for example:

my_list['active'] # {'type': 'boolean', 'string': 'Active'}

or when you don't sure that the specific key exists use the get() method. It will return None if there is no key with the specified name. To get the output you want, here's a quick solution:

for elem in my_list:
    output = f'{my_list[elem]["string"]}: {elem}, {my_list[elem]["type"]}'
    is_help = my_list[elem].get("help")
    if is_help:
        output = f'{output}, {is_help}'
    print(output)

this will be printed:

Active: active, boolean
Title: name, char
Description: description, html
Priority: priority, selection
Product: product, char, Selected product by user