I'm trying to figure out why my loop is printing everything in the dict and not just the values
films = {
"2005": ["Munich", "Steven Spielberg"],
"2006": [["The Prestige", "Christopher Nolan"], ["The Departed", "Martin Scorsese"]]
}
for year in movies:
print (year)
for x in films[year]:
print (films[year])
I would like it to print like this
2005
Munich, Steven Spielberg
2006
The prestige, Christopher Nolan
the Departed, Martin Scorsese
But instead its printing like this with brackets and apostrophes
2005
['Munich', 'Steven Spielberg']
You're not using x (I suggest a better name).
This code works in both Python 2.7 and Python 3.x:
films = {
"2005": ["Munich", "Steven Spielberg"],
"2006": [["The Prestige", "Christopher Nolan"], ["The Departed", "Martin Scorsese"]]
}
for year in sorted(films.keys()):
print(year)
if isinstance(films[year][0], list):
films_list = films[year]
else:
films_list = [films[year]]
for film in films_list:
print(", ".join(film))
print("")
Instead of
print (films[year])
use
print (", ".join(films[x]))
This construction joins members of the list films[x] (yes - [x], not [year]) using the string
", " (comma and a space) as separators between individual members.
Related
Need help, a follow up question from one of my previous but a little over my head. I have a list of tuples (s) and a dictionary (dct). For each one of the keys in (s), I need to return a list of tuples containing the matching group key in (dct) and matching key in (s) if the condition below is met:
Condition:
All elements in at least 1 list within a specific group in (dct) is present in the string in (s). if True, return a list of tuples containing the associated group in (dct) and key in (s)
s = [('[0]',
'good morning i live in the city same day deliveries my wille at salmon today will be there today i have an easy ride'),
('[0, 1]',
"christmas is upon us and my father is the greatest of all time and i will celebrate his greatness sad to hear she left"),
('[0]',
'excited to be here i am a boy. thanks man my name is joe", "i live in a city'),
('[0]',
'greetings, today is a good day i go to the village and learn i receive a scholarship')]
dct = {
"group1": [
["i am a boy", "my name is joe", "i live in a city"],
["my name is sam", "i go to school"],
],
"group2": [
["i a stranger", "my present sister", "i love people"],
["my father is here"],
["i go to the village", "i receive a scholarship"],
],
"group3": [
[
"i live in the city",
"my wille at salmon today",
"i have an easy ride",
],
["my father is the greatest", "sad to hear she left"],
[
"today is her birth day",
"i will eat the rice",
"tomorrow is her day",
],
],
}
Expected Results:
[('[0]': 'group3'), ('[0, 1]': 'group3'), ('[0]': 'group1'), ('[0]': 'group2')]
My attempt:
# function to return key for any value
def get_key(val):
for key, value in s.items():
if val == value:
return key
return "key doesn't exist"
out = []
for k, v in dct.items():
for lst in v:
if all(item in s.get('[0,1]') for item in lst):
out[k] = get_key(s.get('[0,1]'))
print(out)
I figured out a solution that works:
out_lst = []
for groupId, lst_lst in dct.items():
for (Id, parag) in s:
for lst in lst_lst:
if all(item in parag for item in lst):
if ((Id, groupId) not in out_lst):
out_lst.append((Id, groupId))
print(out_lst)
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be
Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]
basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section
my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]
print("All Available Genres " + str(my_list))
Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]
variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]
user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
This is quite ugly, but I've tried not to change it too much:
my_list= ["Horror", "Action", "Comedy", "Thriller", "Mystery", "Fantasy", "Sci-fi", "Romance", "Drama", "Dystopian"]
print("All Available Genres " + str(my_list))
movies = {
"Anabelle": ["Horror", "Triller"],
"Criminal_Minds": ["Mystery", "Drama"],
"Avengers": ["Action", "Fantasy", "Sci-fi"],
"Scooby_doo": ["Comedy", "Horror"],
"Brooklyn_99": ["Action", "Comedy" ],
"The_fault_in_our_stars": ["Romance", "Drama"],
"The_tomorrow_war": ["Drama", "Sci-Fi"],
"Maze_Runner": ["Drama", "Dystopian", "Thriller"],
"Hunger_Game": ["Dystopian", "Sci-Fi", "Thriller"],
"Harry_Potter": ["Mystery", "Fantasy"],
"Fast_Furious": ["Action"],
"Conjuring": ["Horror"],
"Fantastic_Beast": ["Fantasy"],
"Parasite": ["Comedy", "Thriller"],
"Space_between_us": ["Romance"],
"Murder_Mystery": ["Romance", "Mystery"],
"The_Purge": ["Dystopian", "Thriller"],
"Spider_Man": ["Action", "Fantasy"],
}
user_genres = (input("What movie/show genre do you like to watch?: "))
user_genres = user_genres.split(", ") if ", " in user_genres else user_genres.split(",")
for (movie, genres) in movies.items():
toPrint = False
for genre in genres:
if genre in user_genres:
toPrint = True
if toPrint:
print(movie + " [" + ", ".join(genres) + "]")
I'm not 100% sure if this is what you are asking for but here is some code that
-iterates through movies
-checks if genre is in each movie''
if it is, prints movie name.
Simply add this to the end of your code
#Splitting user request
user_genre_s = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
movies_found = 0
print(f"The following movies were found for genres {user_genre}:")
for movie in newlist:
#testing if value was found in each movie's list
for genre in user_genre_s:
if genre in movie:
print(variable_strings[newlist.index(movie)].replace("_"," "))#printing movie name if found, replacing underscores with spaces to make it look nicer
movies_found += 1
if movies_found == 0:
print(":( no match was found")#Telling user if none are found.
However you may want to lower() all of the genres as users may not enter capitals
I have a code that should write information to excel using selenium. I have 1 list with some information. I need to write all this to excel, and i have solution. But, when i tried to use it i got 'DataFrame' object is not callable. How can i solve it?
All this code into iteration:
for schools in List: #in the List i have data from excel file with Name of schools
data = pd.DataFrame()
data({
"School Name":School_list_result[0::17],
"Principal":School_list_result[1::17],
"Principal's E-mail":School_list_result[2::17],
"Type":School_list_result[8::17],
"Grade Span": School_list_result[3::17],
"Address":School_list_result[4::17],
"Phone":School_list_result[14::17],
"Website":School_list_result[13::17],
"Associations/Communities":School_list_result[5::17],
"GreatSchools Summary Rating":School_list_result[6::17],
"U.S.News Rankings":School_list_result[12::17],
"Total # Students":School_list_result[15::17],
"Full-Time Teachers":School_list_result[16::17],
"Student/Teacher Ratio":School_list_result[17::17],
"Charter":School_list_result[9::17],
"Enrollment by Race/Ethnicity": School_list_result[7::17],
"Enrollment by Gender":School_list_result[10::17],
"Enrollment by Grade":School_list_result[11::17],
})
data.to_excel("D:\Schools.xlsx")
In School_list_result i have this data:
'Cape Elizabeth High School',
'Mr. Jeffrey Shedd',
'No data.',
'9-12',
'345 Ocean House Road, Cape Elizabeth, ME 04107',
'Cape Elizabeth Public Schools',
'8/10',
'White\n91%\nAsian\n3%\nTwo or more races\n3%\nHispanic\n3%\nBlack\n1%',
'Regular school',
'No',
' Male Female\n Students 281 252',
' 9 10 11 12\n Students 139 135 117 142',
'#5,667 in National Rankings',
'https://cehs.cape.k12.me.us/',
'Tel: (207)799-3309',
'516 students',
'47 teachers',
'11:1',
Please follow the syntax about how to create a dataframe
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
So your code should be modified as:
for schools in List: #in the List i have data from excel file with Name of schools
data = pd.DataFrame(data={
"School Name": School_list_result[0::17],
"Principal": School_list_result[1::17],
"Principal's E-mail": School_list_result[2::17],
"Type": School_list_result[8::17],
"Grade Span": School_list_result[3::17],
"Address": School_list_result[4::17],
"Phone": School_list_result[14::17],
"Website": School_list_result[13::17],
"Associations/Communities": School_list_result[5::17],
"GreatSchools Summary Rating": School_list_result[6::17],
"U.S.News Rankings": School_list_result[12::17],
"Total # Students": School_list_result[15::17],
"Full-Time Teachers": School_list_result[16::17],
"Student/Teacher Ratio": School_list_result[17::17],
"Charter": School_list_result[9::17],
"Enrollment by Race/Ethnicity": School_list_result[7::17],
"Enrollment by Gender": School_list_result[10::17],
"Enrollment by Grade": School_list_result[11::17],
})
Do you want to add in an existing xlsx file?
First, create the dictionary and then call the DataFrame method, like this:
r = {"column1":["data"], "column2":["data"]}
data = pd.DataFrame(r)
I'm trying to make it say 'author' died in 'date', but it won't work.
authors = {
"Charles Dickens": "1870",
"William Thackeray": "1863",
"Anthony Trollope": "1882",
"Gerard Manley Hopkins": "1889"
}
for author, date in authors.items():
print( "%s" % authors + " died in " + date)
You just need to change the name of the variable inside the print from authors (your full dict) to author, representing each instance of the collection:
authors = {
"Charles Dickens": "1870",
"William Thackeray": "1863",
"Anthony Trollope": "1882",
"Gerard Manley Hopkins": "1889"
}
for author, date in authors.items():
print( "%s" % author + " died in " + date)
This produces the following output:
Charles Dickens died in 1870
William Thackeray died in 1863
Anthony Trollope died in 1882
Gerard Manley Hopkins died in 1889
here is the simple and easy to understand solution
for author, date in authors.items():
print( author + " died in " + date)
output
Charles Dickens died in 1870
William Thackeray died in 1863
Anthony Trollope died in 1882
Gerard Manley Hopkins died in 1889
for author, date in authors.items():
print( "%s" % author + " died in " + date)
You can use format for that
authors = {
"Charles Dickens": "1870",
"William Thackeray": "1863",
"Anthony Trollope": "1882",
"Gerard Manley Hopkins": "1889"
}
for author, date in authors.items():
print('{}, in {}'.format(author, date)))
Or f-string Python 3.6 and above
for author, date in authors.items():
print('{author}, in {date}'))
Output
Charles Dickens, in 1870
William Thackeray, in 1863
Anthony Trollope, in 1882
Gerard Manley Hopkins, in 1889
You need to change the authors in print statement to author,
you can use multiple styles of print for your purpose choose one of them wisely,
authors = {
"Charles Dickens": "1870",
"William Thackeray": "1863",
"Anthony Trollope": "1882",
"Gerard Manley Hopkins": "1889"
}
for author, date in authors.items():
#your statement
print( "%s" % author + " died in " + date)
#using f before the string for python 3.6 and above
print(f"{author} died in {date}")
#using format() method of string
print("{0} died in {1}".format(author,date))
#using string concatenation
print(author + " died in "+date)
Every statement prints same output but some techniques are more useful than others such as using f or format() gives you more flexibility.
Hope this helps you!
I have a function that takes a list of Books and returns one large string of each book followed by a newline character.
Book = namedtuple('Book', 'author title genre year price instock')
Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)
I made the following function:
def Booklist_display(dlist):
for item in dlist:
return '{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock)
But it only prints the first book and not the second book.
Suzane Collins 6.96 20
Can someone help me understand if I have the code correct and why my function just prints the first part only? I can't seem to pin point the logic.
In this for loop:
for item in dlist:
return '{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock)
The function exits when the loop iterates over the first object (because of return).
Store the result in a list and return later:
strlist = []
for item in dlist:
strlist.append('{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock))
return '\n'.join(strlist)
You can use join together with a list comprehension.
from collections import named tuple
Book = namedtuple('Book', 'author title genre year price instock')
books = [Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]
def Booklist_display(dlist):
return '\n'.join(['{title} {price} {stock}'
.format(title=item.title, price=item.price, stock=item.instock)
for item in dlist])
>>> Booklist_display(books)
"The Hunger Games 6.96 20\nHarry Potter and the Sorcerer's Stone 4.78 12"