jscionti jscionti - 9 days ago 7
Python Question

Python adding unwanted double quotes to a dictionary

After passing a string into a function, Python is generating additional double quotes. For example:

def main():
...
foo("string1", "'string2','string3'")
...
def foo(var1, var2):
dictionary = {
'a' : var1,
'b' : [var2]
}
print(dictionary)


I need var2 to be in square brackets for what comes next. The following is the output:

{'a': 'string1', 'b': ["'string2','string3'"]}


How can the additional double quotes be removed so that
'b': ['string2','string3']
?

Answer
'b' : [x[1:-1] for x in var2.split(",")]

split separates the substrings, and [1:-1] removes the quotes.