[Python] Retrieve the main key by using part of the sub value in a dictionary

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

  1. Stack

    Stack Membro Participativo

    I have a dictionary which has subkeys and sub values. I want to print a list of the main keys that contain a certain value in the subkey. I hope the example makes it clear:

    cssStyleDict= {'.c13':{'color':'#000',
    'font-family':'"Arial"',
    'font-weight':'700',
    'vertical-align':'baseline'},
    '.c6':{'font-weight':'700'},
    '.c7':{'color':'#000',
    'font-size':'11pt',
    'font-weight':'700',
    'text-decoration':'none'},
    '.c2':{'background-color':'#ff0'}}


    I want to print a list of all keys that contain {'font-weight':'700'}. I have tried this:

    def getKeysByValue(dictOfElements, valueToFind):
    listOfKeys = list()
    listOfItems = dictOfElements.items()
    for item in listOfItems:
    if item[1] == valueToFind:
    listOfKeys.append(item[0])
    return listOfKeys

    listOfKeys = getKeysByValue(cssStyleDict, {'font-weight':'700'} )
    for key in listOfKeys:
    print(key)


    But of course this only gives me an exact match. I've also tried using a regex expression, but to no avail. The output should be a list containing .c13 .c6 .c7

    Thanks in advance if anyone can help.

    Continue reading...

Compartilhe esta Página