How to translate this working code the python way

Viewed 79

For standard response purposes, I need to convert a string from this:

[(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)]

to this:

[{"words": "Ethyl,alcohol", "score": 1.0}, {"words": "clean,water", "score": 1.0}]

I was able to code it correctly but my code doesn't seems like "pythony".. Here is my code:

lst = []
for data in dataList:
    dct = {}
    dct['words'] = data[0][0] + ',' + data[0][1]
    dct['score'] = data[1]
    lst.append(dct)

sResult = json.dumps(lst)
print(sResult)

Is my code acceptable? I will be dealing with this more often and would like to see a more readable way the python way.

2 Answers

Try this using comprehension:

dataList = [(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)]

[{'words': ','.join(x), 'score': y} for x, y in dataList]

output:

[{'words': 'Ethyl,alcohol', 'score': 1.0},
 {'words': 'clean,water', 'score': 1.0}]

The 2 ways that you can use to shorten your code, not more readable for sure, but this can be prefered, are

  • inline a dict construction

    lst = []
    for data in dataList:
        lst.append({'words': data[0][0] + ',' + data[0][1], 'score' : data[1]})
    
  • Use a list comprehension

     lst = [{'words': data[0][0] + ',' + data[0][1], 'score': data[1]} for data in dataList]
    
Related