0

I want to compare 2 Python response strings and print out the differences, here is my code right now:

import requests import json import time

getFirst = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1") liveRN = json.dumps(getFirst.json(), indent=4)

while True: get = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1") dataPretty = json.dumps(get.json(), indent=4) data = get.json()

if get.status_code == 200:
    print("ok")
if dataPretty != data:
    for item in data:
        if str(item) not in liveRN:
            send = 1
            print(f"Found difference: {item}")

            symbol = item['symbol']
            img = item['image']
            name = item['name']
            description = item['description']

            print(symbol)
            print(img)
            print(name)
                         
        else:
            print("Didnt find")
else:
    print("No change")

time.sleep(15)

I only want to print the items when the two repsonses dont match but right now its printing the items I want even when the strings do match.

I tried to see add another if condition where if the 2 request response match it wont do anything and just pass but that didnt work

1 Answer 1

0

You can use sets to find whether items of the dictionary are changed or not. I've used the compare code from another question but this is somewhat what you can use for your problem

import requests 
import time

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    shared_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
    same = set(o for o in shared_keys if d1[o] == d2[o])
    return added, removed, modified, same

first = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1").json()[0]

while True: 
    get_second = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1")

    if get_second.status_code == 200:
        print("ok")

    second = get_second.json()[0]
    added, removed, modified, same = dict_compare(first, second)

    if len(added) > 0 or len(modified) > 0  or len(removed) > 0:
        print("added: ", added)
        print("modified: ", modified)
        print("removed: ", removed)
    else:
        print("No change")
        
    time.sleep(15)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.