Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get id from dictionary where value is the same as the one I want?

    data =
{ "skusToId": [
        {
            "skus": [
                "SKU321",
                "SKU618",
                "SKU1443"
            ],
            "id": 0
        },
        {
            "skus": [
                "SKU1874"
            ],
            "id": 1
        },
        {
            "skus": [
                "SKU9322",
                "SKU9097",
                "SKU978" ,
                "SKU321"
            ],
            "id": 2
        }
}

lets say I have a list of skus, something like:

sku_list = [SKU321, SKU1443, SKU1874]
I would like to know how to get the ids where I find that sku. Note that a SKU can be found in multiple ids. Like SKU321.

What I’m trying is: by using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for elem in sku_list:
   foo = [v['id'] for v in data if data['skus'] == elem][0]
   print(foo)  

but this only returns me:

KeyError: 'skus'

where in fact I need something like alist of ids where I can find that SKU.

>Solution :

Depending on what you want you output to be

Just a check

sku_list = ['SKU321', 'SKU1443', 'SKU1874']
for obj in data['skusToId']:
   print(obj , any(map(lambda e: e in obj['skus'], sku_list)) )

which skus

 for obj in data['skusToId']:
     print(obj['id'], [e for e in obj['skus'] if e in sku_list] )
0 ['SKU321', 'SKU1443']
1 ['SKU1874']
2 ['SKU321']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading