简体   繁体   中英

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"})'

Those two strings are valid Python dict literals. So let's convert them to dict objects:

a = '{"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"}'

b = '{"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"}'

import ast
a = ast.literal_eval(a)
b = ast.literal_eval(b)

...and then just compare them:

print(a==b)   # prints:  True

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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