Home > OS >  Find the unique values in a python string variable and separate with a comma, for a SQL criteria
Find the unique values in a python string variable and separate with a comma, for a SQL criteria

Time:11-09

Morning,

I need to retrieve the unique elements in a string which will be used as part of a SQL criteria.

sales_code_string_RFQ =  'AAA','BBB','CCC','DDD','AAA','EEE',.......

Goal is to get a unique list of sales codes from sales_code_string_RFQ separated by a , The following works but seems to be inefficient. Any suggestions to improve?

# Covert string to list
sales_code_string_RFQ = sales_code_string_RFQ.split(',')
print('2. Split sales_code_string_RFQ:')
print(sales_code_string_RFQ)

["'AAA'", "'BBB'", "'CCC'", "'DDD'", "'AAA'", "'EEE'".....]

print('3. Get unique values and convert to list:')
sales_code_string_RFQ = list(set(sales_code_string_RFQ))
print(sales_code_string_RFQ)

["'AAA'", "'BBB'", "'CCC'", "'DDD'", "'EEE'".....]

print('4.Covert list to string:')
sales_code_string_RFQ = ",".join(sales_code_string_RFQ)
print(sales_code_string_RFQ)
print("", end='\n')

Final correct output:

'AAA', 'BBB', 'CCC', 'DDD',  'EEE' ,....

CodePudding user response:

Assuming you have a list of sales codes like this:

sales_codes = ["'AAA'", "'BBB'", "'CCC'", "'DDD'", "'AAA'", "'EEE'"]

The built-in Python class set will sort the list for you and take only unique items from it:

unique_codes = set(sales_codes)

Then you can join them together to form your query criterion:

criterion = ', '.join(set(sales_codes))
  • Related