Reputation: 121
Have been struggling now couple hours to lowercase objects with Python. To use str lowercase function I need to convert it to the string. Can I someway convert it back to JSON? Because now there is just three objects in list which are strings.
My code:
from fastapi import FastAPI, Query, Depends
from typing import Optional, List
robots = [
{'name': 'ABB', 'short': 'ABB'},
{'name': 'Techman Robots', 'short': 'TM'},
{'name': 'Mobile Industry Robots', 'short': 'MIR'},
]
@app.get('/robots')
def get_courses(lower: Optional[int] = None):
cs = robots
if lower == 1:
cs = []
for c in robots:
joku = str(c).lower()
cs.append(joku)
return {'Robots': cs}
I want the results be like this:
{'name': 'abb', 'short': 'abb'},
{'name': 'techman robots', 'short': 'tm'},
{'name': 'mobile industry robots', 'short': 'mir'},
I hope you understand what I mean. Sorry little language barrier. Thanks guys.
Upvotes: 0
Views: 3353
Reputation: 2129
robots
is a list
of dictionaries
, so try the following
robots
dictionary
key
in dictionary, convert them to lowercase using .lower()
This should do it:
robots = [
{'name': 'ABB', 'short': 'ABB'},
{'name': 'Techman Robots', 'short': 'TM'},
{'name': 'Mobile Industry Robots', 'short': 'MIR'},
]
new_robots = []
for mdict in robots:
new_dict = {}
for key, value in mdict.items():
new_dict[key] = value.lower()
new_robots.append(new_dict)
print(robots)
or in one line
new_robots = [{key: value.lower() for key, value in mdict.items()} for mdict in robots]
Output:
[{'name': 'abb', 'short': 'abb'}, {'name': 'techman robots', 'short': 'tm'}, {'name': 'mobile industry robots', 'short': 'mir'}]
Upvotes: 3
Reputation: 121
Got this working with ast:
import ast
@app.get('/robots')
def get_courses(lower: Optional[int] = None):
cs = robots
if lower == 1:
cs = []
for c in robots:
finallyWorking= ast.literal_eval(str(c).lower())
cs.append(finallyWorking)
return {'Robots': cs}
Upvotes: 0