Python - Getting Items From List Using Day Name - python

I am trying to make a program that gets the date, works out what lessons i have.
import datetime
def getdate():
now = datetime.datetime.now()
print(now.strftime("%A"))
day=getdate()
##LESSON LIST###
################
Lessons = [
Monday=['English','Geography','German','P.E.','Science-C']
Tuesday=['Art','Science-B','Maths','ICT','French']
Wednesday=['History','English','Drama','Science-B','Maths']
Thursday=['P.E.','D&T','HTT','Geography','R.E.']
Friday=['German','D&T','Maths','English','Music']
]
################
#END LESSON LIST
Today = Lessons[day]
print("1) Book Check")
print("2) Timetable List")
x = input()
if x = 1:
#List lessons for this day one by one with a book input eg.
print("book for lesson1")
l1 = bool(input("True/False"))
print("book for lesson2")
l2 = bool(input("True/False"))
#but it should say the lesson name, and save the state of book boolean
elif x = 2:
#list lessons for this day
print(Today) # just an example.
Currently, I get a syntax error that I cannot fix, I can't find where I have gone wrong. I would like to use a dictionary to complete my code but I am unsure how to.

First you have a major error in how you are trying to form a dict. It should be this:
Lessons = {
'Monday':['English','Geography','German','P.E.','Science-C'],
'Tuesday':['Art','Science-B','Maths','ICT','French'],
'Wednesday':['History','English','Drama','Science-B','Maths'],
'Thursday':['P.E.','D&T','HTT','Geography','R.E.'],
'Friday':['German','D&T','Maths','English','Music']
}
This is a dictionary called Lessons that has Strings as keys (the days of the weeks) and Lists as values (The lists of lessons). To access a list of lessons you would do it like so:
Lessons['Monday']
Note that this returns a list, if you want it formatted differently, then you can do something like this:
", ".join(Lessons['Monday'])
This will give you a comma-separated list of lessons.
I am unsure what exactly you are trying to do with books, but if you want to be more specific I will update my answer. However, I can say that if you will be running this program each day, then you will need to store information about the books in a file to maintain their state, otherwise it will be lost when the program ends.
Also, variables should be lower-cased (lessons instead of Lessons), but I kept it how you had it to be consistent.

Related

How can I add two or more elements to a list from a single input in Python?

What my script is doing now is adding elements to a list. For example, if the user types "JO", I will add "John" to the list. What I want to do now is that, if the user types "2 JO", I add two elements to the list: "John" and "John".
This is how the database looks like now:
Sample database copy.png
This is the code now:
import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input(Please type what you want to add: )
list1.append(name[incoming_msg])
I need to do it all from the same input, I cannot ask separately for quantity and abbreviation. I wanted to know if there is any library that can do this somehow easily because I am a beginner coder. If there is no library but you have any idea how I could solve it, it would be awesome as well.
Thank you so much in advance!
you can use string.split() to split the string by space into a list then use the first element to multiply a list that contains the value from the dictionary and increment it to the result list. see the code
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
list1.append(name[incoming_msg[0]])

Dictionary entry not working as intended, only last entry getting inserted-Python

Working on this for learning experience. The 3 ideas below I came up with
A) User creates a profile so I have a dictionary for fname and lname.
B)Then I randomly generate userid add that to a list. This list only contains random user id that I will user later eg: userid012,userid89
C) I assign A and B in a new dictionary. Output looks like this:
used_id user3
profile {'lastname': 'jon', 'firstname': 'jme'}
problem: I only see the last values user id and names. If I have more than 2 entries, I do not see the 1st ones. Helpful hint would be really helpful.
Thank You.
import random
print('Enter choice 1-3:'),'\n'
print('', '1-Create new profile','\n',
'2-Update existing profile','\n',
'3-Delete a profile')
#global variables
choice=int(input())
user_directory={}
#Dictionary function that takes fst and lst name and puts in a dict:
def new_profile():
new_profile={}
fn=input('First name:')
new_profile['firstname']=fn
ln = input('Last name:')
new_profile['lastname'] = ln
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
#Generates a random user id which we will assign to a user created above
def user_id():
uid_list=[]
user_id='user'+str(random.randint(0,101))
uid_list.append(user_id)
if(user_id in uid_list):
uid_list.remove(user_id)
user_id = 'user' + str(random.randint(0, 101))
uid_list.append(user_id)
return user_id
#This dictionary will have user id and associate created new_profile
def addToDict():
#user_directory={} unable to use this making it global
user_directory['used_id']=user_id()
user_directory['profile']=new_profile()
for key,value in user_directory.items():
user_directory[key]=value
return user_directory
if(choice==1):
# myuser=addToDict() this appraoch did not work
#addToDict>> adding it here will not get this option in while loop, put inside while
while True:
addToDict()
print('Add another entry?')
choice=input()
#Put the line below to see if number increases
print('Current', len(user_directory)-1)
if(choice!='stop'):
continue
else:
break
for k,v in user_directory.items():
print(k,v)
Bad indentation in the last line of new_profile(). The return is running on the first iteration. Try:
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
Btw, you don't seem to be following most conventions/standards in Python. Take a look at this simple tutorial about PEP, the official style guide. This way you can make better looking code and we can help faster :)
Your code contains a couple of bugs. I can only guess what you want to do. Lets start with the obvious: The function addToDict() should probably add a new user to the dictionary.
What you usually want is to have a dictionary which maps a user_id onto a profile:
def addUserToDict(user_dictionary, user_id, profile):
user_directory[user_id] = profile
And then in the input loop below you call this function with your dictionary, a new user id and a new profile.
A second bug is in user_id(): You always return a list with one new element, with a new random user id. And you always discard the first generated user id and then you add a second one.

Python parse an xml file pass result to array

I am attempting to parse an xml file which I have accomplished and pass the results into an array which will be used later on. The xml is opened read and parsed where I am picking out 3 elements (channel, start and title). As shown in code below, the start is date and time. I am able to split date and time and store in date. As the code loops thru each xml entry I would like to pick out the channel, start and title and store to a multidimensional array. I have done this in Brightscript but can't understand the array or list structure of Python. Once I have all entries in the array or list, I will need to parse that array pulling out all titles and dates with the same date. Can somebody guide me thru this?
xmldoc=minidom.parse (xmldoc)
programmes= xmldoc.getElementsByTagName("programme")
def getNodeText(node):
nodelist = node.childNodes
result = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
result.append(node.data)
return ''.join(result)
title = xmldoc.getElementsByTagName("title")[0]
#print("Node Name : %s" % title.nodeName)
#print("Node Value : %s \n" % getNodeText(title))
programmes = xmldoc.getElementsByTagName("programme")
for programme in programmes:
cid = programme.getAttribute("channel")
starts=programme.getAttribute("start")
cutdate=starts[0:15]
year= int(cutdate[0:4])
month= int(cutdate[5:6])
day= int(cutdate[7:8])
hour= int(cutdate[9:10])
minute= int(cutdate[11:12])
sec= int(cutdate[13:14])
date=datetime(year, month, day,hour, minute, sec)
title = programme.getElementsByTagName("title")[0]
print("id:%s, title:%s, starts:%s" %
(cid, getNodeText(title), starts))
print (date)
Python normally refers to arrays as lists and it looks like what you want is a list of lists (there's an array module and the whole numpy extension with its own arrays, but it doesn't look like you want that:-).
So start the desired list as empty:
results = []
and where you now just print things, append them to the list:
results.append([cid, getNodeText(title), date])
(or whatever -- your indentation is so rambling it would cause tons of syntax errors in Python and confuses me about what exactly you want:-).
Now for the part
I will need to parse that array pulling out all titles and dates with
the same date
just sort the results by date:
import operator
results.sort(key=operator.itemgetter(2))
then group by that:
import itertools
for date, items in itertools.groupby(results, operator.itemgetter(2)):
print(date,[it[1] for it in items])
or whatever else you want to do with this grouping.
You could improve this style in many ways but this does appear to give you the key functionality you're asking for.

ArcMap Field Calculator Program to create Unique ID's

I'm using the Field Calculator in ArcMap and
I need to create a unique ID for every storm drain in my county.
An ID Should look something like this: 16-I-003
The first number is the municipal number which is in the column/field titled "Munic"
The letter is using the letter in the column/field titled "Point"
The last number is simply just 1 to however many drains there are in a municipality.
So far I have:
rec=0
def autoIncrement()
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
return "16-I-" '{0:03}'.format(rec)
So you can see that I have manually been typing in the municipal number, the letter, and the hyphens. But I would like to use the fields: Munic and Point so I don't have to manually type them in each time it changes.
I'm a beginner when it comes to python and ArcMap, so please dumb things down a little.
I'm not familiar with the ArcMap, so can't directly help you, but you might just change your function to a generator as such:
def StormDrainIDGenerator():
rec = 0
while (rec < 99):
rec += 1
yield "16-I-" '{0:03}'.format(rec)
If you are ok with that, then parameterize the generator to accept the Munic and Point values and use them in your formatting string. You probably should also parameterize the ending value as well.
Use of a generator will allow you to drop it into any later expression that accepts an iterable, so you could create a list of such simply by saying list(StormDrainIDGenerator()).
Is your question on how to get Munic and Point values into the string ID? using .format()?
I think you can use following code to do that.
def autoIncrement(a,b):
global rec
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
r = "{1}-{2}-{0:03}".format(a,b,rec)
return r
and call
autoIncrement( !Munic! , !Point! )
The r = "{1}-{2}-{0:03}".format(a,b,rec) just replaces the {}s with values of variables a,b which are actually the values of Munic and Point passed to the function.

Dictionary of father son names with options for user and outputs name of son, father, or grandfather

I'm trying to make this file into two dictionary to access with the input of the user and I am completely lost. Sad to say I have been working on this for a couple of weeks now. I have the file read and and know how to set up the options for input, just not how to get a certain name based off of what the user option and name is.
Here is my code thus far:
sonfather = {}
fatherson = {}
names = open('names.dat', 'r')
sonfather = names.read().split(',')
print sonfather
print "Father/Son Finder"
print "0 - Quit"
print "1 - Find a Father"
print "2 - Find a Grandfather"
print "3 - Find a Son"
print "4 - Find a Grandson"
print "5 - List of names"
control = ""
while control != "quit":
choice = input("Enter your choice here: ")
if choice == 0:
control = "quit"
elif choice == 1:
print input("Enter the name of the son :")
names = open('names.dat', 'r')
sonfather = names.read().split(',')
print sonfather
you have to understand what type an object is, in order to properly use anything dictionary related to it. because you arent going to get dictionary type things unless its a dictionary type.
sonfather at the time of print is a list. it is a list that contains strings.
you need to do SOMETHING to that list, that will "change" it to a dictionary. just because it has "KEY:VALUE" it does not mean its a dictionary. its a string.
SO for starters, you may want to just split each of them at the colon.
sonfather = [x.split(':') for x in sonfather]
this [x for x in blabla] thing is list comprehension, it might be a lil bit advanced... but it does the same thing as this:
new_sonfather = []
for item in sonfather:
new_sonfather.append(item.split(":"))
sonfather = new_sonfather
this iterates over each item in sonfather replacing it (note for advanced pythonistas: i know not really...) with a list in this form "son:father" becomes ['son','father']
THEN you have something that looks like this
sonfather = [['son1','father1'],['son2','father2'],['son3','father3'],['son4','father4']]
this is ALMOST where you want it to be.
THEN it gets super magical up in here.
convert that sucker to a dictionary from here
son_father_dictionary = dict(sonfather)
aww snaps son.
AT THIS POINT it son_father_dictionary is a TRUE official card carrying member of the dictionary club.
so if you were to do something crazy like:
print(son_father_dictionary['son1'])
the output would be father1

Categories

Resources