How to use 'for' loop to split values and create list of dictionaries? - python-3.x

Disclaimer: I am an absolute beginner in Python programming so please bear with me. I am taking a class for this and extremely desperate to get help.
I am creating a program that can read data from ANY text file which contains information like so:
Produce, Is it a fruit (Y/N)
String: "Apple","Y""Banana","Y""Pumpkin","N""Orange","Y""Eggplant","N"...
I need to convert the string to a list that will look like this:
"Apple","Y"
"Banana","Y"
"Pumpkin","N"
...
After that, I have to split/separate the values so they can fit into a dictionary that will look like this:
{"produce": xxx,"fruit": Yes/No}
For this task, I was told that I need to use the for loop to split the lines and create a list of dictionaries. But, I don't know how and where to put it.
Note that the program must be able to read data from any file. The user must also be able to modify whether the listed fruit/veg is indeed a fruit or not.
Thank you so much in advance!

I hope this is what you want...
string="apple","Y","banana","Y","pumpkin","N"
dict={}
for i in range(0,len(string),2):
dict[string[i]]=string[i+1]
for k,v in dict.items():
print(k,v)

So here I am after a lot of comments,
here is the suggested solution and this will work
x = "Apple","Y""Banana","Y""Pumpkin","N""Orange","Y""Eggplant","N"
length = len(x)
mainList = []
def split_str(s):
return [ch for ch in s]
for i in range(length):
dict = {}
if (i == 0):
dict["produce"] = x[i]
if(split_str(x[i+1])[0] == 'Y'):
dict["fruit"] = 'Yes'
else:
dict["fruit"] = 'No'
mainList.append(dict)
else:
if(i < 5):
dict["produce"] = x[i][1:]
if(split_str(x[i+1])[0] == 'Y'):
dict["fruit"] = 'Yes'
else:
dict["fruit"] = 'No'
mainList.append(dict)
print(mainList)
online fiddle link:
https://pyfiddle.io/fiddle/b3de895b-8542-419d-841a-ad7ddf008d9a/?i=true

Thank you so much for those who answered my question. I was able to run this properly using the following codes:
# Read the contents from the file first.
def get_content(filename):
f = open(filename,"r")
if f.mode == 'r':
content = f.read()
content = content.replace('"','')
return content
# Convert the contents to list of dictionaries (Y/N being a boolean).
def convert_to_list(content):
string = sorted(content.split('\n'),key=str.lower)
produce_list = []
for x in string:
a = x.split(',')
b: bool = bool('Y' in a[1])
d = dict({'produce': a[0], 'fruit':b})
restaurant_list.append(d)
return restaurant_list
I was able to complete this with help outside the site. Thank you so much for everyone's input!

Related

Read out .csv and hand results to a dictionary

I am learning some coding, and I am stuck with an error I can't explain. Basically I want to read out a .csv file with birth statistics from the US to figure out the most popular name in the time recorded.
My code looks like this:
# 0:Id, 1: Name, 2: Year, 3: Gender, 4: State, 5: Count
names = {} # initialise dict names
maximum = 0 # store for maximum
l = []
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
try:
name = l[1]
if name in names:
names[name] = int(names[name]) + int(l(5))
else:
names[name] = int(l(5))
except:
continue
print(names)
max(names)
def max(values):
for i in values:
if names[i] > maximum:
names[i] = maximum
else:
continue
return(maximum)
print(maximum)
It seems like the dictionary does not take any values at all since the print command does not return anything. Where did I go wrong (incidentally, the filepath is correct, it takes a while to get the result since the .csv is quite big. So my assumption is that I somehow made a mistake writing into the dictionary, but I was staring at the code for a while now and I don't see it!)
A few suggestions to improve your code:
names = {} # initialise dict names
maximum = 0 # store for maximum
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
names[name] = names.get(name, 0) + l[5]
maximum = [(v,k) for k,v in names]
maximum.sort(reversed=True)
print(maximum[0])
You will want to look into Python dictionaries and learn about get. It helps you accomplish the objective of making your names dictionary in less lines of codes (more Pythonic).
Also, you used def to generate a function but you never called that function. That is why it's not printing.
I propose the shorted code above. Ask if you have questions!
Figured it out.
I think there were a few flow issues: I called a function before defining it... is that an issue or is python okay with that?
Also I think I used max as a name for a variable, but there is a built-in function with the same name, that might cause an issue I guess?! Same with value
This is my final code:
names = {} # initialise dict names
l = []
def maxval(val):
maxname = max(val.items(), key=lambda x : x[1])
return maxname
with open("filepath", "r") as file:
for line in file:
l = line.strip().split(",")
name = l[1]
try:
names[name] = names.get(name, 0) + int(l[5])
except:
continue
#print(str(l))
#print(names)
print(maxval(names))

How to parse CSV files into a dictionary and use them one by one (without using the CSV library)

I have a homework assignment that essentially requires you to parse a CSV file (preferably without using the CSV library, but really whatever's easiest is fine) and move its contents into a dictionary, and from that dictionary print certain parts and use other parts as answers.
I've tried this method:
with open('questions.txt') as f:
questions={}
for line in f:
csvvalues = line.split(',')
csvvalues = [x.rstrip() for x in csvvalues]
questions[csvvalues[-1]] = {
'Q' : csvvalues[0],
'A' : csvvalues[1:len(csvvalues)-1]
}
print(questions)
But the formatting came out very weird and unusable.
Here is the code I have so far:
quiz={}
f=open("questions.txt","r")
for line in f:
parts=line.split(",")
quiz[parts[0]]=[parts[1],parts[2],parts[3],parts[4].strip("\n")]
for i in range(10):
print(quiz)
ans=input("Input your answer")
if ans==quiz[parts[5]]:
print("Correct!")
else:
print("Nope, the answer is")
f.close()
But it comes up with a KeyError, and both questions (see my file for context) come out at the same time, which I don't want - they should come one at a time.
Expected results:
Which birthstone is associated with the month of May? Diamond, Ruby, Emerald, Sapphire
Input your answer <user inputs answer>
Correct! (or)
Nope, the right answer is (correct answer as A B C or D)
(then next question is outputted)
MY CSV FILE: ("questions")
Which birthstone is associated with the month of May?,Diamond,Ruby,Emerald,Sapphire,C
Which two colours as on the flag of Poland?,Red and Green, Blue and White, Green and White, Red and White,D
If you really don't want to use third-party libraries:
def parse_csv(file_name: str) -> dict:
retval = {}
with open(file_name) as f:
for line in f:
data = line.strip().split(',')
key, *values = (v.strip() for v in data)
retval[key] = values
return retval
questions = parse_csv('questions.txt')
for question, answers in questions.items():
correct = answers[-1]
answers = answers[:-1]
result = input(f"{question}: {','.join(answers)}")
if result == correct:
print('Yeah, mate!')
else:
print(f'The correct answer is {correct!r}')

Python 3, else causing syntax error

Hi all so i have this piece of code in python 3:
def spss_script_3tests (dictionary):
inv_test_dict = {v: k for k , v in dictionary.items()}
for i in excel_log_absent['Pupil\nID/Barcode ']:
pupil_id=(i.split('-'))[2]
test_no=(i.split('-'))[1]
#index in spss data of pupil id
spss_pid_index=spss_pupilid.index[spss_pupilid[('PupilID',)] == pupil_id].tolist()
# if t1 name in spss = t1 number in excel using dictionary
if (spss_pupilid[('T1name',)][spss_pid_index] == dictionary[test_no]).iloc[0]:
print('if PupilID = ',"'",pupil_id,"'",' Attendlog1 = 1',sep='')
print('if PupilID = ',"'",pupil_id,"'",' testnum1 = ',test_no,sep='')
else:
print('if PupilID = ',"'",pupil_id,"'",' Attendlog2 = 1',sep='')
print('if PupilID = ',"'",pupil_id,"'",' testnum2 = ',inv_test_dict[spss_pupilid[('T2name',)][spss_pid_index[0]]],sep='')
else:
alot of useless info but the last else:is flagging up a syntax error and i have no idea why. As far as i know everything that's indented should be, every ( and [ is accounted for and a print statement works fine there but a condition (else, if, while) doesn't.
Any help would be much appreicated
You can have a issue with the identation or just you don't get the point of the else. With a simple else all the data that doesn't enter in your first if will enter in the else.
You can create a else if in python is elif your code should look similar to this:
if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)

Extracting integer values from a string on Python

I've been through every post I could find on the subject and nothing have answered my problem;
This is the code:
output = 'Scan results for BrainS (192.168.43.111)
Scan results for Slave (192.168.43.107)
Scan results for SlaveSmall (192.168.43.242)'
while (True)
if output[i].isdigit(): # i has initial value of 15, j=0
f[j]=output[i]
j+=1
i+=1
elsif(i == len(output)):
break
else:
i+=1
continue
Print:
>>>f
['1','9','2','1','6','8','4','3','1','1','1','0','0','0']
As you can see I'm trying to extract the IP as it is with dots(in this code I didnt try to extract the dots but only the numbers),
I cant figure out how do get the string I want exactly as it is:
f = 192.168.43.111
Any suggestions? better commands?
For multiple pairs of parenthesis in the string I think it is best to use a regex like so:
import re
output = '''Scan results for BrainS (192.168.43.111)
Scan results for Slave (192.168.43.107)
Scan results for SlaveSmall (192.168.43.242)'''
f = re.findall(r'\(([^()]+)\)',output)
>>>['192.168.43.111', '192.168.43.107', '192.168.43.242']
Try it here!
Here you go, this code will do the job!
output = 'My computer IP is = (192.168.43.111) and yours not.'
ip=[]
ip_flag = False
for x in output:
if x == '(':
ip_flag = True
continue
if ip_flag:
if x != ')':
if x != '.': # remove this line of you want the dots
ip.append(x)
else:
break
print(ip)
theIp=""
for i in ip:
theIp+=i

How to check if a value in a variable in a list held in another variable

import csv
samsung = ['samsung','s1','s2','s3','s4','s5','s6','s7','galaxy']
iphone = ['iphone']
problemTypes = []
solution = []
instruction = []
def solve():
def foundProblem():
for queryPart in whatProblem:
for problem in problemTypes:
if queryPart == problem:
return True
solved = False
readCSV = csv.reader(csvfile, delimiter = ',')
for row in readCSV:
solution = row[0]
problemTypes = row[1].split()
instruction = row[2]
if foundProblem():
print('The solution is to '+solution)
print(instruction)
solved = True
if solved == False:
print('Solution not found.\nPlease contact your supplier')
whatProblem = str(input('What seems to be the issue with your smartphone?\n')).lower().split()
version = input('What type of phone do you have?\n').lower().split()
if version == iphone:
with open('iPhone.csv') as csvfile:
solve()
elif version in samsung:
with open('samsung.csv') as csvfile:
solve()
else:
print('Phone not supported')
This is an attempt at creating a trouble shooter using multiple csv files however I am met with the problem of the samsung part. It seems that it cannot notice that the input is actually part of the samsung variable. I am new here so if I have formatted this wrong please notify me and if the solution is extremely simple please know I am new to coding.
Try at least to change this line:
version = input('What type of phone do you have?\n').lower().split()
into:
version = input('What type of phone do you have?\n').lower().split()[0]
But reading input you currently force the user to enter 'samsung' which is not the most accessible approach. Keep on learning and trying and it will work out fine!
It's not entirely clear which bit you're having a problem with, but this extract looks wrong:
with open('iPhone.csv') as csvfile:
solve()
You probably intend to use csvfile within the block:
with open('iPhone.csv') as csvfile:
solve(csvfile)
and to change the implementation of solve to accept csvfile as an argument. As it is, it looks like you're trying (and failing) to communicate via a global variable; even if that did work, it's a poor practice that leads to unmaintainable code!
I'm not sure exactly what your problem is either but maybe try this statement instead of your other elif statement:
elif any(version in s for s in samsung):
Check if a Python list item contains a string inside another string

Resources