[Python] How to print the subkey if it has a value [closed]

Discussão em 'Python' iniciado por Stack, Abril 30, 2025.

  1. Stack

    Stack Membro Participativo

    Greeting, I only want to print the subkey(s) if it has a value. Below is my code:

    my_dict = {
    'a': {
    'subkey_a': 1
    },
    'b': 2,
    'c': {
    'subkey_c': 3
    },
    'd': {
    'subkey_d': ''
    }
    }

    for key, value in my_dict.items():
    if isinstance(value, dict) and value != '':
    print(f"Key '{key}' has subkeys and values") # subkey_d should not be printed!


    I don't want to print the subkey_d since there is no value. The output:

    Key 'a' has subkeys and values
    Key 'c' has subkeys and values
    Key 'd' has subkeys and values


    what I did wrong?

    Continue reading...

Compartilhe esta Página