简体   繁体   English

在python中使用字典中的部分子值检索主键

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

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'} .我想打印包含{'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输出应该是一个包含.c13 .c6 .c7的列表

Thanks in advance if anyone can help.如果有人可以提供帮助,请提前致谢。

You can try this way:你可以试试这个方法:

>>> [ i for i in cssStyleDict if cssStyleDict[i].get('font-weight') == '700' ]
['.c13', '.c6', '.c7']

To use the code that you've posted as a base for your answer, you only need to change the condition of the if-statement.要使用您发布的代码作为答案的基础,您只需更改 if 语句的条件。 Currently, you are checking for a perfect match because you have used “==“目前,您正在检查完美匹配,因为您使用了“==”

However, Python comes with a great operator that does exactly what you need: “in”.然而,Python 附带了一个很棒的运算符,它可以完全满足您的需求:“in”。

Thus, your new condition should be:因此,您的新情况应该是:

        If valueToFind in item[1]:

Hope this makes sense!希望这是有道理的!

Clean and Clear Approach using dictonary built-ins.使用字典内置的清洁和清晰的方法。

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'}}

for key, val in cssStyleDict.items():
  if(cssStyleDict[key].__contains__('font-weight')):
    if(cssStyleDict[key]['font-weight'] == '700'):
      print(key)

I would do it by first checking each dict for that key, then comparing the value to the expected one.我会首先检查该键的每个字典,然后将值与预期的值进行比较。

def getKeysByValue(dictOfElements, valueToFind):
    listOfKeys = list()
    listOfItems = dictOfElements.items()
    for k,v in listOfItems:
        try:
            if v[valueToFind[0]] == valueToFind[1]:
                listOfKeys.append(k)
        except KeyError:
            pass
    return  listOfKeys

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM