How do I categorize items in a list? - list

dataset = ['Apple', 'Banana', 'Mango', 'Grape', 'Pineapple',
'Lettuce', 'Cabbage', 'Spinach', 'Carrot', 'Cauliflower']
ran = random.choice(dataset)
fruit = ['Apple', 'Banana', 'Mango', 'Grape', 'Pineapple']
vegetable = ['Lettuce', 'Cabbage', 'Spinach', 'Carrot', 'Cauliflower']
if ran == vegetable:
print('HINT: It is a vegetable!')
else:
print('HINT: It is a fruit!')
First I categorized items in a list but when I run my code it would only say the else statement.

You have to check if it is in the list, an example:
import random
dataset = ['Apple', 'Banana', 'Mango', 'Grape', 'Pineapple',
'Lettuce', 'Cabbage', 'Spinach', 'Carrot', 'Cauliflower']
ran = random.choice(dataset)
fruit = ['Apple', 'Banana', 'Mango', 'Grape', 'Pineapple']
vegetable = ['Lettuce', 'Cabbage', 'Spinach', 'Carrot', 'Cauliflower']
print(ran) // To verify the item
if ran in fruit:
print("Fruit")
elif ran in vegetable:
print("Vegetable")
else:
print("Unknown")

I think its because your asking if the random element, is equal to the entire "Vegetable" array, and in this case it is not, so it will return false.
Do a for loop where you loop over each element of the vegetable array (Or use an inbuilt function of a library to check if the ran elemet is contained in the vegetable array), and check the element againsed your ran variable, then if it is equal, you can print('Hint: it is a vegetable') and break out of the loop, if its not, your else statement will trigger and run: print('HINT: It is a fruit!')
:)
The only case it should return "Vegetables, (in the provided information) is if ran = ['Apple', 'Banana', 'Mango', 'Grape', 'Pineapple',
'Lettuce', 'Cabbage', 'Spinach', 'Carrot', 'Cauliflower']
(The vegetable array/dataset)

Related

How to return nested list from html forms usingf pydantic?

Trying to return form data in a nested list. Current code returns the below format:
{
"name":"meal number 4",
"description":"new description",
"ing_qty":"4",
"ing_type":"small",
"ing_name":"Tomato",
"ing_id":"9"
}
Printing raw FormData results in:
FormData([('name', 'meal number 4'), ('description', 'new
description'), ('ing_qty', '4'), ('ing_type', 'small'), ('ing_name',
'Onion'), ('ing_id', '6'), ('ing_qty', '4'), ('ing_type', 'small'),
('ing_name' , 'Red'), ('ing_id', '7'), ('ing_qty', '4'), ('ing_type',
'small'), ('ing_name', 'Tomato'), ('ing_id', '8'), ('ing_qty', '4'),
('ing_type', 'small'), ('ing_name', 'Tomato'), ('ing_id', '9')])
I am trying to get the results into the below format so that i may update my db recrds with the form data.
{
"name":"string",
"description":"string",
"ingredients":[
{
"ing_id":null,
"ing_qty":null,
"ing_type":null,
"ing_name":null
}
]
}
Here are my Pydantic BaseModels
class IngUpdate(BaseModel):
ing_id: Optional[int]
ing_qty: Optional[int]
ing_type: Optional[str]
ing_name: Optional[str]
class RecipeUpdate(BaseModel):
name: Optional[str]
description: Optional[str]
ingredients: List[IngUpdate] = []
Here is my Post Request:
#router.post("/edit/{recipe_id}")
async def edit_select_recipe(request: Request, recipe_id: int,
db: Session = Depends(get_db)):
data = await request.form()
print(data)
return data
Adding Response Model to Post returns the following result:
{
"name":"meal number 4",
"description":"new description",
"ingredients":[
]
}
It appears it's unable to pull the data into a list. How can I get this into a nest model?

Django only returns last row of dict in template

I am trying to return the values from a Dict in Django.
My views.py prints the the correct data in the terminal when doing a GET-request to my page, however, in my template I only get the last line of the dictionary.
I have tried looping the dict in my template and all sorts of combinations but I can't seem to make it work. Am I missing something? For instance, in the template below I print the entire dict. But it still only prints the last row somehow.
views.py
fruits = [
'Apple', 'Banana', 'Orange']
for fruit in fruits:
price_change = historical_prices['price_change'][::-1]
low_price = 0
for day in price_change:
if day < -0.1:
low_price += 1
else:
break
if low_price >= 0:
ls_dict = {'fruit': fruit, 'low_price': low_price}
print(ls_dict)
return render(request, "prices/index.html", {
"ls_dict": ls_dict,
})
Template
<p>{{ ls_dict }}</p>
Template output
{'fruit': 'Orange', 'low_price': 1}
Correct print which views.py produces
{'fruit': 'Apple', 'low_price': 1}
{'fruit': 'Banana', 'low_price': 3}
{'fruit': 'Orange', 'low_price': 1}
The print() seems correct, but you are just overriding the variable over and over again, thus ls_dict will only be the set with the last iteration of the for loop.
You can test this by print(ls_dict) outside of the for-loop
Try the following:
ls_list = []
for fruit in fruits:
price_change = historical_prices['price_change'][::-1]
low_price = 0
for day in price_change:
if day < -0.1:
low_price += 1
else:
break
if low_price >= 0:
ls_dict = {'fruit': fruit, 'low_price': low_price}
ls_list.append(ls_dict)
return render(request, "prices/index.html", {
"ls_list": ls_list,
})

Extract key values from multiple lists of dictionaries python

I have multiple empty lists and dict in side list. I need to extract dict key values in list.
Example:
l =([{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}, [], []])
expected result:
k = ['UK', 'PT', 'UK', 'IT', 'PT', 'FR', 'FR']

Regular expression for a list of string objects

I have a list as following:
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
My code is as following
import re
[item2 for item in list12 for item2 in item.split() if not re.match("^[*A-Z]+(0-9){4}$", item2)]
I got output like :
['First', 'Company', 'limited', 'Apple', 'Technology', 'Sami']
I expect the output to be like :
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
I am not good with regular expression. How can I reach to my required solution?
A non-regex way in python,
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
str = " ".join(list12)
list21 = str.split()
res = [k.strip('*') for k in list21 if '**' not in k]
print(res)
Output:
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
DEMO: http://tpcg.io/s9aBhe
Seems you're looking for
\b([A-Za-z]+)\b
In Python:
import re
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
rx = re.compile(r'\b([A-Za-z]+)\b')
result = [word for item in list12 for word in rx.findall(item)]
print(result)
Which yields
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']

Why is this dictionary overwriting itself during for loop?

I have a bit of code that is trying to transform a dictionary from one nesting format to another using a series of for loops so that I can easily export the dictionary to a CSV file. However, as my script loops through the input dict, it overwrites the output dict rather than appending the additional values, and I can't figure out why.
Here's the format of the input dictionary:
{'data': [{'title': 'Lifetime Likes by Country',
'values': [{'end_time': '2013-11-10T08:00:00+0000',
'value': {'IN': 343818, 'PK': 212632, 'US': 886367}},
{'end_time': '2013-11-11T08:00:00+0000',
'value': {'IN': 344025, 'US': 886485}}]},
{'title': 'Daily Country: People Talking About This',
'values': [{'end_time': '2013-11-10T08:00:00+0000',
'value': {'IN': 289, 'US': 829}},
{'end_time': '2013-11-11T08:00:00+0000',
'value': {'IN': 262, 'US': 836}}]}]}
Here's my code:
input_dict = function_to_get_input_dict()
filtered_dict = {}
for metric in input_dict['data']:
for day in metric['values']:
parsed_date = parser.parse(day['end_time'])
date_key = parsed_date.strftime('%m/%d/%Y')
filtered_dict[date_key] = {}
filtered_dict[date_key]['Total %s' % metric['title']] = 0
for k, v in day['value'].iteritems():
filtered_dict[date_key]['%s : %s' % (metric['title'], k)] = v
filtered_dict[date_key]['Total %s' % metric['title']] += v
pprint(filtered_dict) #debug
Expected output dictionary format:
{date1:{metric_1_each_country_code:value, metric_1_all_country_total:value, metric_2_each_country_code:value, metric_2_all_country_total:value}, date2:{etc}}
However, instead I'm getting an output dictionary that only has one metric per date:
{date1:{metric_2_each_country_code:value, metric_2_all_country_total:value}, date2:{etc}}
It appears to be overwriting the metric key:value pair each time, which I don't understand because the key's should be unique to each metric using the ['%s : %s' % (metric['title'], k)] formula, so they shouldn't get overwritten.
What am I missing?
If you notice in your code, in the second for loop you have filtered_dict[date_key] = {}. This resets the value of filtered_dict[date_key] instead of allowing you to add to it.
input_dict = function_to_get_input_dict()
filtered_dict = {}
for metric in input_dict['data']:
for day in metric['values']:
parsed_date = parser.parse(day['end_time'])
date_key = parsed_date.strftime('%m/%d/%Y')
filtered_dict[date_key] = {}
filtered_dict[date_key]['Total %s' % metric['title']] = 0
for k, v in day['value'].iteritems():
filtered_dict[date_key]['%s : %s' % (metric['title'], k)] = v
filtered_dict[date_key]['Total %s' % metric['title']] += v
pprint(filtered_dict) #debug
I think one problem is that your data has syntax errors in it and it is nearly impossible to see the structure. I have corrected it and pretty printed the whole thing to help you better see its structure. Not a complete answer, but it goes a long way towards helping solve the problem:
import pprint; pprint.pprint({"data": [{ "values": [{ "value": { "US": 886367, "IN": 343818, "PK": 212632}, "end_time": "2013-11-10T08:00:00+0000"},{"value": { "US": 886485, "IN": 344025}, "end_time": "2013-11-11T08:00:00+0000"}], "title": "Lifetime Likes by Country"}, {"values": [{"value": { "US": 829, "IN": 289}, "end_time": "2013-11-10T08:00:00+0000"},{"value": {"US": 836,"IN": 262}, "end_time": "2013-11-11T08:00:00+0000"}], "title": "Daily Country: People Talking About This"}]})
{'data': [{'title': 'Lifetime Likes by Country',
'values': [{'end_time': '2013-11-10T08:00:00+0000',
'value': {'IN': 343818, 'PK': 212632, 'US': 886367}},
{'end_time': '2013-11-11T08:00:00+0000',
'value': {'IN': 344025, 'US': 886485}}]},
{'title': 'Daily Country: People Talking About This',
'values': [{'end_time': '2013-11-10T08:00:00+0000',
'value': {'IN': 289, 'US': 829}},
{'end_time': '2013-11-11T08:00:00+0000',
'value': {'IN': 262, 'US': 836}}]}]}
Now that I can see the nature of your data, perhaps this type of data structure would better suit your needs:
import pprint; pprint.pprint({'Daily Country: People Talking About This': {'2013-11-11T08:00:00+0000': {'US': 836, 'IN': 262}, '2013-11-10T08:00:00+0000': {'US': 829, 'IN': 289}}, 'Lifetime Likes by Country': {'2013-11-11T08:00:00+0000': {'US': 886485, 'IN': 344025}, '2013-11-10T08:00:00+0000': {'PK': 212632, 'US': 886367, 'IN': 343818}}})
Which gives you:
{'Daily Country: People Talking About This': {'2013-11-10T08:00:00+0000': {'IN': 289,
'US': 829},
'2013-11-11T08:00:00+0000': {'IN': 262,
'US': 836}},
'Lifetime Likes by Country': {'2013-11-10T08:00:00+0000': {'IN': 343818,
'PK': 212632,
'US': 886367},
'2013-11-11T08:00:00+0000': {'IN': 344025,
'US': 886485}}}