简体   繁体   English

在嵌套字典中搜索特定键?

[英]Search for specific key in nested dictionary?

I have 2 barcode scanners that i need to check against a nested dictionary.我有 2 个条形码扫描仪,需要对照嵌套字典进行检查。

First i need to find the key that corresponds with the matching 'Outer' barcode from scanner1.首先,我需要从scanner1 中找到与匹配的“外部”条形码对应的密钥。

Than i need to run the key and find the corresponding 'Inner' barcode, then compare the result to scanner2 to see if they match.比我需要运行密钥并找到相应的“内部”条形码,然后将结果与扫描仪 2 进行比较以查看它们是否匹配。 This checks we have the correct items in a carton.这会检查我们在纸箱中是否有正确的物品。

I have tried a few examples but they don't seem to work.我尝试了一些示例,但它们似乎不起作用。

When i run this i only get None returned.当我运行它时,我只得到 None 返回。

This is part of my dictionary that i have to search.这是我必须搜索的字典的一部分。

    barcodes = {1: {'Outer': '10000261344131', 'Inner': '26214092', 'Lane': '3', 'Group': '1'},
               2: {'Outer': '10000261343905', 'Inner': '26134390', 'Lane': '3', 'Group': '1'},
               3: {'Outer': '10000261343769', 'Inner': '26134376', 'Lane': '1', 'Group': '1'},
               4: {'Outer': '14088700046026', 'Inner': '4088700046029', 'Lane': '0', 'Group': '0'},
               5: {'Outer': '19100010090011', 'Inner': '9100010090011', 'Lane': '1', 'Group': '0'},
               6: {'Outer': '19300601775283', 'Inner': '9300601775286', 'Lane': '1', 'Group': '0'},
               7: {'Outer': '19300633223844', 'Inner': '9300633223847', 'Lane': '1', 'Group': '0'}}

    scanner1 = '19300633223844'
    scanner2 = '9300633223847'

    def search(values, searchFor):
            for k in values:
                for v in values[k]:
                    if searchFor in v:
                        return k
            return None

        #Checking if string 'Mary' exists in dictionary value
        groupfind = search(barcodes, str(scanner1))

First i need to find the key that corresponds with the matching 'Outer' barcode from scanner1.首先,我需要从scanner1 中找到与匹配的“外部”条形码对应的密钥。

matches = [k for k, v in barcodes.items() if v["Outer"] == scanner1]

Than i need to run the key and find the corresponding 'Inner' barcode, then compare the result to scanner2 to see if they match.比我需要运行密钥并找到相应的“内部”条形码,然后将结果与扫描仪 2 进行比较以查看它们是否匹配。 This checks we have the correct items in a carton.这会检查我们在纸箱中是否有正确的物品。

if matches:
    key = matches[0]  # Assumes only 1 match can be found in the first step.
    if barcodes[key]["Inner"] == scanner2:
        print("Inner matches scanner2")
    else:
        print("Inner doesn't match scanner2"]

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

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