Search code examples
pythonstringartifactory-query-lang

Is is possible to compare strings with different order using python3


I have two strings (which are actually AQL). is there a way I can compare between them even if the order is not the same (I want to get true for the below as all values are equal)?

'items.find({"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"})'

'items.find({"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"})'

Solution

  • Starting with:

    input_1 = 'items.find({"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"})'
    input_2 = 'items.find({"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"})'
    

    Strip the items.find() call from around the dict:

    input_1 = input_1[11:-1]
    input_2 = input_2[11:-1]
    

    or if you want to be more general:

    input_1 = input_1[input_1.find('{'):input_1.rfind('}')+1]
    input_2 = input_2[input_2.find('{'):input_2.rfind('}')+1]
    

    As far as determining equality of the two dictionary strings from that point, they must be converted into actual dictionaries.

    You can use the the method suggested by jez (ast.literal_eval()) if you like, though I personally would use json.loads() for this purpose:

    import json
    
    dict_1 = json.loads(input_1)
    dict_2 = json.loads(input_2)
    

    Then you simply compare the two dictionaries:

    dict_1 == dict_2
    

    Which in this case will return True