Asim Zaidi
Asim Zaidi

Reputation: 28284

python foreach loop and dictionaries

I am getting my feet wet with python. I have an issue. I have one array and one dictionary and I am trying to match the data between them. I am coming form php background so I may get the terminology wrong while I try to learn python. So here we go.

product = [{'id': 57L, 'product_name': '3-Piece Reversible Bonded Leather Match Sofa Set in Cream'}, {'id': 58L, 'product_name': '3-Piece Sage Microfiber Sectional Sofa Set with Faux Leather Ottoman'}, {'id': 663L, 'product_name': 'Recycled Plastic Adirondack Tete-a-tete'}, {'id': 717L, 'product_name': 'Designer 20-Bottle Wine Cabinet'}]

then I am loading a json file into dictionary like this

productsChecked = json.loads(open('/Library/WebServer/Documents/scrapper/test2.json').read())

and looping over productsChecked gives me something like this if I do print

{u'price': u'$399.00', u'product_name': u'Glendale Brown PU Leather Ottoman with Pull-out Guest Bed', u'availability': u'In Stock'}

so I have now this

productsChecked = json.loads(open('/Library/WebServer/Documents/scrapper/test2.json').read())
for key, value in enumerate(productsChecked):
    for v in value.iteritems():
        print v

so that gives me this

(u'price', u'$93.00')
(u'product_name', u'Espresso Hand-Woven Cane Panel 2-Door Wall-Hanging Bathroom Cabinet')
(u'availability', u'In Stock')

I am not sure what that means...I wanted to get the product_name from above and wanted to compare it with product_name from the first product array and if the product_name from the json/dictionary matched the product_name from product array then I wanted to print out product_name matched but now I am not sure where to go from here

Upvotes: 0

Views: 743

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122242

productsChecked is just a list of dictionaries, so you can access the product_name key directly:

productsChecked = json.load(open('/Library/WebServer/Documents/scrapper/test2.json'))

print productsChecked[0]['product_name']

You can check if any item in products matches with any():

for check_product in productsChecked:
    if any(p['product_name'] == check_product['product_name'] for p in product):
        # match!

or you can search for the matching product with a loop:

for check_product in productsChecked:
    for prod in product:
        if prod['product_name'] == check_product['product_name']:
            print 'Match:', prod

which matches multiple product entries and gives you the matching dictionary.

This does all get inefficient fast; you are looping over both lists, creating N*M loops. You can reduce that by turning your initial product list into a dictionary for fast O(1) constant time lookups:

products_map = {p['product_name']: p for p in product}

This does assume that product names are unique.

Now you can just look up the product name directly:

for check_product in productsChecked:
    if check_product['product_name'] in products_map:
        # the named product is in our map

Upvotes: 4

Related Questions