initially i had to create a function that receives the person's attributes and returns a structure that looks like that:
Team:
Name: Real Madrid
President:
Name: Florentino Perez
Age: 70
Country: Spain
Office: 001
Coach:
Name: Carlo Ancelotti
Age: 55
Country: Italy
Office: 006
Coach License: 456789545678
Players:
- Name: Cristiano Ronaldo
Age: 30
Country: Portugal
Number: 7
Position: Forward
Golden Balls: 1
- Name: Chicharito
Age: 28
Country: Mexico
Number: 14
Position: Forward
- Name: James Rodriguez
Age: 22
Country: Colombia
Number: 10
Position: Midfielder
- Name: Lucas Modric
Age: 28
Country: Croatia
Number: 19
Position: Midfielder
This structure also contains info about other clubs . I managed to do this with the following function:
def create_person(name, age, country, **kwargs):
info={"Name": name, "Age": age, "Country": country}
for k,v in kwargs.iteritems():
info[k]=v
return info
I used this function to create a list of nested dictionaries and display the right structure for each team. Example:
teams = [
{
"Club Name": "Real Madrid",
"Club President": create_person("Florentino Perez", 70, "Spain", Office="001"),
"Club's Coach": create_person("Carlo Angelotii", 60, "Italy", Office="006", CoachLicense="456789545678"),
"Players": {
"Real_Player1": create_person("Cristiani Ronaldo", 30, "Portugal", Number="7", Position="Forward", GoldenBalls="1"),
"Real_Player2": create_person("Chicharito", 28, "Mexic", Number="14", Position="Forward"),
"Real_Player3": create_person("James Rodriguez", 22, "Columbia", Number="10", Position="Midfilder"),
"Real_Player4": create_person("Lucas Modric", 28, "Croatia", Number="19", Position="Midfilder")
}
},
{
"Club Name": "Barcelona",
"Club President": create_person("Josep Maria Bartolomeu", 60, "Spain", Office="B123"),
"Club's Coach": create_person("Luis Enrique Martinez", 43, "Spain", Office="B405", CoachLicense="22282321231"),
"Players": {
"Barcelona_Player1": create_person("Lionel Messi", 28, "Argentina", Number="10", Position="Forward", GoldenBalls="3"),
"Barcelona_Player2": create_person("Xavi Hernandez", 34, "Spain", Number="6", Position="Midfilder"),
"Barcelona_Player3": create_person("Dani Alvez", 28, "Brasil", Number="22", Position="Defender"),
"Barcelona_Player4": create_person("Gerard Pique", 29, "Spain", Number="22", Position="Defender")
}
}
]
Everything fine so far.
The part where I got stuck is this: Create a function print_president that receives the team name prints the following output:
Team: Real Madrid
President: Florentino Perez
Age: 70
Country: Spain
Office: 001
I could use a variable to display this but i need a function and I don't know how to work around this. Please help!
When you're trying to solve a problem (or ask a question) first simplify as much as you can. Your print_president() function takes a team name and then prints various pieces of information about the team. Each team is a dictionary with various attributes. So a simplified version of the problem might look like this:
teams = [
{
'name': 'Real Madrid',
'pres': 'Florentino',
},
{
'name': 'Barcelona',
'pres': 'Josep',
},
]
def print_president(team_name):
for t in teams:
# Now, you finish the rest. What should we check here?
...
print_president('Barcelona')
I can't think of a way to do this with just a team name, as you will have to know which dict to look at. I think something like this:
def print_president(team):
print 'Team: {team} President: {president} Age: {age} Country: {country} Office: {office}'.format(
team=team['Club Name'],
president=team['Club President']['Name'],
age=team['Club President']['Age'],
country=team['Club President']['Country'],
office=team['Club President']['Office']
)
If you are thinking of looking through all the teams in the list, then pass in two arguments: teams_list and team_name:
def print_president(teams_list,team_name):
for team in teams_list:
if team_name in team.values():
print 'Team: {team} President: {president} Age: {age} Country: {country} Office: {office}'.format(
team=team['Club Name'],
president=team['Club President']['Name'],
age=team['Club President']['Age'],
country=team['Club President']['Country'],
office=team['Club President']['Office']
)
Related
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)
Just a heads up I'm completely new to the coding scene and I'm having some issues using a json file
I've got the json to open using
json_queue = json.load(open('customer.json'))
but I just cant find the right code that allows me to make use of the info on the json. I think its because the json is an array not an object (probably completely wrong) My json currently looks like this
[
["James", "VW"],
["Katherine", "BMW"],
["Deborah", "renault"],
["Marguerite", "ford"],
["Kenneth", "VW"],
["Ronald", "Mercedes"],
["Donald", "BMW"],
["Al", "vauxhall"],
["Max", "porsche"],
["Carlos", "BMW"],
["Barry", "ford"],
["Donald", "renault"]
]
What I'm trying to do is take the persons name and the car type they are looking for and compare it too another json file that has the stock of cars in a shop but I'm currently stuck as to how I get python to actually use the information in that json.
I think I might of over explained my problem. My issue is that I am just starting a project using .json files and I can get python to open the file, but then I am unsure of how to get python to read that "James" wants a "VW" and then to go check the stock json to check if it is in stock. The stock json looks like this.
{
"VW": 4,
"BMW": 2,
"renault": 0,
"ford": 1,
"mercedes": 2,
"vauxhall": 1,
"porsche": 0,
}
What you have after the json.load() call is a plain python list of lists:
whishlist = [
["James", "VW"],
["Katherine", "BMW"],
["Deborah", "renault"],
["Marguerite", "ford"],
["Kenneth", "VW"],
["Ronald", "Mercedes"],
["Donald", "BMW"],
["Al", "vauxhall"],
["Max", "porsche"],
["Carlos", "BMW"],
["Barry", "ford"],
["Donald", "renault"]
]
where each sublist is a , pair. You can iterate over this list:
for name, car in whishlist:
print("name : {} - car : {}".format(name, car))
Now with your "other json file", what you have is a dict:
stock = {
"VW": 4,
"BMW": 2,
"renault": 0,
"ford": 1,
"mercedes": 2,
"vauxhall": 1,
"porsche": 0,
}
so all you have to do is to iterate over the whishlist list, check whether the car is in stock and print (or do anything else) the result:
for name, car in whishlist:
in_stock = stock.get(car, 0)
print("for {} : car {} in stock : {}".format(name, car, in_stock))
for James : car VW in stock : 4
for Katherine : car BMW in stock : 2
for Deborah : car renault in stock : 0
for Marguerite : car ford in stock : 1
for Kenneth : car VW in stock : 4
for Ronald : car Mercedes in stock : 0
for Donald : car BMW in stock : 2
for Al : car vauxhall in stock : 1
for Max : car porsche in stock : 0
for Carlos : car BMW in stock : 2
for Barry : car ford in stock : 1
for Donald : car renault in stock : 0
I have just started coding this semester, so if you can use simple methods to help me find my answer I'd appreciate it. Basically, I just want it to print the name of each dictionary and then list it's contents. Oh, and just so you know, I don't actually even like sports this was just a previous homework assignment that I wanted to improve upon. Here's what I've got and yes, I know it doesn't work the way I want it to:
football = {
'favorite player': 'Troy Aikman',
'team': 'Dallas Cowboys',
'number': '8',
'position': 'quarterback'
}
baseball = {
'favorite player': 'Jackie Robinson',
'team': 'Brooklyn Dodgers',
'number': '42',
'position': 'second baseman'
}
hockey = {
'favorite player': 'Wayne Gretzky',
'team': 'New York Rangers',
'number': '99',
'position': 'center'
}
sports = [football, baseball, hockey]
my_sports = ['Football', 'Baseball', 'Hockey']
for my_sport in my_sports:
print(my_sport)
for sport in sports:
for question, answer in sport.items():
print(question.title + ": " + answer)
print("\n")
I want it to print:
Football
Favorite player: Troy Aikman
Team: Dallas Cowboys
Number: 8
Position: quarterback
Baseball:
Favorite player: Jackie Robinson
Team: Brooklyn Dodgers
Number: 42
Position: second baseman
...and so forth. How do I achieve the results I want? The simpler the better and please use Python 3, I know nothing of Python 2.
my_sports = {'Football': football, 'Baseball' : baseball, 'Hockey' : hockey}
for key,value in my_sports.items():
print(key)
for question, answer in value.items():
print(question + ": " + answer)
print("\n")
You can try this:
sports = {"football":football, "baseball":baseball, "hockey":hockey}
for a, b in sports.items():
print(a)
for c, d in b.items():
print("{}: {}".format(c, d))
Output:
football
position: quarterback
favorite player: Troy Aikman
number: 8
team: Dallas Cowboys
baseball
position: second baseman
favorite player: Jackie Robinson
number: 42
team: Brooklyn Dodgers
hockey
position: center
favorite player: Wayne Gretzky
number: 99
team: New York Rangers
UPDATED:
I edit my answer and now the code below works:
my_sports = {'Football': football, 'Baseball' : baseball, 'Hockey' : hockey}
for key,value in my_sports.items():
print(key)
for question, answer in value.items():
print(question + ": " + answer)
print("\n")
This is the result:
Football
Favorite Player: Troy Aikman
Team: Dallas Cowboys
Number: 8
Position: quarterback
Baseball
Favorite Player: Jackie Robinson
Team: Brooklyn Dodgers
Number: 42
Position: second baseman
Hockey
Favorite Player: Wayne Gretzky
Team: New York Rangers
Number: 99
Position: center
Code here:
https://repl.it/MOBO/3
The built-in zip function seems like the easiest way to combine and pair-up elements from the two lists. Here's how to use it:
sports = [football, baseball, hockey]
my_sports = ['Football', 'Baseball', 'Hockey']
for my_sport, sport in zip(my_sports, sports):
print('\n'.join((
'{}', # name of sport
'Favorite player: {favorite player}',
'Team: {team}',
'Number: {number}',
'Position: {position}')).format(my_sport, **sport) + '\n'
)
I've looked over this many times, and cant seem to find the problem with it.
I am trying to pull 3 fields from a JSON response (engagements, shares, comments), sum them together, then print the sum.
It seems to be returning the fields correctly, but it returns zero in the final print.
I'm very new to this stuff, but would appreciate any help anyone can give me. I'm guessing there is something fundamental I am missing here.
import urllib2,time,csv,json,requests,urlparse,pdb
SEARCH_URL = urllib2.unquote("http://soyuz.elastic.tubularlabs.net:9200/intelligence/video/_search?q=channel_youtube_id:""%s""%20AND%20published:%3E20150715T000000Z%20AND%20published:%3C20150716T000000Z")
reader = csv.reader(open('input.csv', 'r+U'), delimiter=',', quoting=csv.QUOTE_NONE)
cookie = {"user": "2|1:0|10:1438908462|4:user|36:eyJhaWQiOiA1Njk3LCAiaWQiOiA2MzQ0fQ==|b5c4b3adbd96e54833bf8656625aedaf715d4905f39373b860c4b4bc98655e9e"}
# idsToProcess = []
# for row in reader:
# if len(row)>0:
# idsToProcess.append(row[0])
idsToProcess = ['qdGW_m8Rim4FeMM29keDEg']
for userID in idsToProcess:
# print "fetching for %s.." % fbid
url = SEARCH_URL % userID
soyuzResponse = None
response = requests.request("GET", url, cookies=cookie)
ret = response.json()
soyuzResponse = ret['hits']['hits'][0]['_source']['youtube']
print soyuzResponse
totalDelta = 0
totalEngagementsVal = 0
totalSharesVal = 0
totalCommentsVal = 0
valuesArr = []
for entry in valuesArr:
arrEngagements = entry['engagements']
arrShares = entry['shares']
arrComments = entry['comments']
if len(arrEngagements)>0:
totalEngagementsVal = arrEngagements
elif len(arrShares)>0:
totalSharesVal = arrShares
elif len(arrComments)>0:
totalCommentsVal = arrComments
print "%s,%s" % (userID,totalEngagementsVal+totalSharesVal+totalCommentsVal)
totalDelta += totalEngagementsVal+totalSharesVal+totalCommentsVal
time.sleep(0)
print "%s,%s" % (userID,totalDelta)
exit()
Here is the json I am parsing:
took: 371,
timed_out: false,
_shards: {
total: 128,
successful: 128,
failed: 0
},
hits: {
total: 1,
max_score: 9.335125,
hits: [
{
_index: "intelligence_v2",
_type: "video",
_id: "jW7mjVdzR_U",
_score: 9.335125,
_source: {
claim: [
"Blucollection%2Buser"
],
topics: [
{
title_non: "Toy",
topic_id: "/m/0138tl",
title: "Toy"
},
{
title_non: "Sofia the First",
topic_id: "/m/0ncq483",
title: "Sofia the First"
}
],
likes: 1045,
duration: 318,
channel_owner_type: "influencer",
category: "Entertainment",
imported: "20150809T230652Z",
title: "Princess Sofia Cash Register Toy Surprise - Play Doh Caja Registradora Disney Sofia the First",
audience_location: [
{
country: "US",
value: 100
}
],
comments: 10,
twitter: {
tweets: 6,
engagements: 6
},
description: "Disney Princess "Sofia Cash Register" toy unboxing review by DisneyCollector. This is the authentic Royal toy of Sofia fit for a little Princess of Enchantia. Young Girls learn early on how mathematics is important in our lives, and learn to do math, developing creativity with a super fun game! Thx 4 watching this "Disney Princess Sofia cash register" unboxing review. In this video i also used Disney Frozen Princess Anna, Nickelodeon Peppa Pig blind bag and plastilina Play-Doh. Revisión del juguete Princesita Sofía Caja Registradora Real para niños y niñas. Las niñas aprenden desde muy temprano cómo las matemáticas es importante en nuestras vidas, y aprenden a hacer matemáticas, el desarrollo de la creatividad con un juego súper divertido! Here's how to say Princess in other languages: printzesa, 公主, prinses, prenses, printsess, princesse, Prinzessin, puteri, banphrionsa, Principesse, principessa, プリンセス, princese, puteri, prinsessa,prinsesse, princesa, công chúa, tywysoges, Princesses Disney, Prinzessinen, 공주, Princesas Disney, Disney πριγκίπισσες, Дисней принцесс, 디즈니 공주, ディズニーのお姫様, Vorstin, koningsdochter, Fürstin, πριγκίπισσα, księżniczka, królewna, принцесса. Here's how register is called in other languages: Caja Registradora de Princesa Sofía, Caisse Enregistreuse Princesse Sofia, Kassa, Registrierkasse Sofia die Erste Auf einmal Prinzessin, Registratore di Cassa di La Principessa Sofia, Caixa Registadora da Princesa Sofia, ηλεκτρονική ταμειακή μηχανή Σοφία η Πριγκίπισσα, 電子式金銭登録機 ちいさなプリンセス ソフィア, София Прекрасная кассовый аппарат, 디즈니주니어 리틀 프린세스 소피아 전자 금전 등록기, máy tính tiền điện tử, daftar uang elektronik, elektronik yazarkasa, Sofia den första kassaapparat leksak, Jej Wysokość Zosia kasa zabawki, Sofia het prinsesje kassa speelgoed, София Първа касов апарат играчка, casa de marcat jucărie Sofia Întâi. Princess Sofia SLEEPOVER Slumber Party - Princesita Sofía Pijamada Real. https://www.youtube.com/watch?v=WSa-Tp7HfyQ Princesita Sofía Castillo Mágico Parlante juguete de niñas. https://www.youtube.com/watch?v=ALQm_3uhIyg Sofia the First Magical Talking Castle Royal Prep Academy. https://www.youtube.com/watch?v=gcUiY0Suzrc Play-Doh Meal Makin' Kitchen with Princess Sofia the First. https://www.youtube.com/watch?v=x_-OxnRXj6g Sofia the First Royal Prep Academy Dolls Character Collection. https://www.youtube.com/watch?v=_kNY6AkSp9g Peppa Pig Picnic Adventure Car With Princess Sofia the First. https://www.youtube.com/watch?v=KIPH3txlq1o Watch "Sofia the First Talking Magic Castle" talking Clover: https://www.youtube.com/watch?v=ALQm_3uhIyg Play-Doh Sofia the First Magic Talking Castle w/ Peppa Pig: https://www.youtube.com/watch?v=-slXqMiDrY0 Play-Doh Sofia the First Going to School Portable Classroom http://www.youtube.com/watch?v=0R-dkVAIUlA",
views: 941726,
channel_network: null,
channel_subscribers: 5054024,
youtube_id: "jW7mjVdzR_U",
facebook: {
engagements: 9,
likes: 2,
shares: 7,
comments: 0
},
location_demo_count: 1,
is_public: true,
engagements: 1070,
channel_country: "US",
demo_count: null,
monetizable: true,
youtube: {
engagements: 1055,
likes: 1045,
comments: 10
},
published: "20150715T100003Z",
channel_youtube_id: "qdGW_m8Rim4FeMM29keDEg"
}
}
]
}
}
Response from terminal after running script:
{u'engagements': 1055, u'likes': 1045, u'comments': 10}
qdGW_m8Rim4FeMM29keDEg,0
qdGW_m8Rim4FeMM29keDEg,0
Your problem is these two lines:
valuesArr = []
for entry in valuesArr:
Because valuesArr is empty, the for loop never iterates, and that's where your totals are being summed.
I have to use nested loops for this exercise.
I have two class lists and need to determine which students are in both classes. I have written the code and it works but now my for loop is iterating over all the students again and prints the results the same as the iteration instead of just the actual students (in both classes). It does work if I put the for students in cs_students in line with the for students in maths_students but then it's not nested.
My code is as follows:
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben", "Audrey", "Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
for student in math_students:
count = 0
for student in cs_students:
if student in math_students:
count +=1
print("Student:", student, "is enrolled in both classes")
print(count, "Students are enrolled in Computer Science and Maths")
My output is:
Student: Sue is enrolled in both classes
Student: Ben is enrolled in both classes
Student: Audrey is enrolled in both classes
Student: Mark is enrolled in both classes
Student: Paul is enrolled in both classes
Student: Julia is enrolled in both classes
Student: Sue is enrolled in both classes
Student: Ben is enrolled in both classes
Student: Audrey is enrolled in both classes
Student: Mark is enrolled in both classes
Student: Paul is enrolled in both classes
Student: Julia is enrolled in both classes and so on.......
6 Students are enrolled in Computer Science and Maths
I think you're looking for something like this:
in_both_classes = []
for math_student in math_students:
for cs_student in cs_students:
if math_student == cs_student:
in_both_classes.append(math_student)
print "There are {} students in both classes: {}".format(
len(in_both_classes),
", ".join(in_both_classes),
)
You used the same variable, student, in both for-loops. Doing that prevents you from comparing the list values with each other.
That, and simple if-statement would do the trick :
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben",
"Audrey","Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
count = 0
for student1 in math_students: #change this to student1
for student2 in cs_students: #change this to student2
if student1 ==student2: #check if student1 is equal to student 2
count +=1
print("Student:", student2, "is enrolled in both classes") #print student2
print(count, "Students are enrolled in Computer Science and Maths")
Now this would output:
>>>
('Student:', 'Audrey', 'is enrolled in both classes')
('Student:', 'Ben', 'is enrolled in both classes')
('Student:', 'Julia', 'is enrolled in both classes')
('Student:', 'Paul', 'is enrolled in both classes')
('Student:', 'Sue', 'is enrolled in both classes')
('Student:', 'Mark', 'is enrolled in both classes')
(6, 'Students are enrolled in Computer Science and Maths')
when you retrieve the two lists, you use the same variable name studnet, you should rename any of them, for instance s1 and s2 and increase count only when s1 equal to s2.
BTW, I have another suggestion, you can use Sets Intersection
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben", "Audrey", "Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
math_set = set(math_students)
cs_set = set(cs_students)
# students in both cs and math
common_set = math_set & cs_set
#the studnets only in cs
only_cs = cs_set - math_set
# the students only in math
only_math = math_set - cs_set
print common_set
print "----"
print only_cs
print "----"
print only_math
Use a list comprehension to filter people that are in both math class and computer science class:
# contains only the students in both original lists
both = [i for i in math_students if i in cs_students]
for student in both:
# interpolating the name of each student in both list
print '{} is enrolled in both classes'.format(student)
# interpolating the number of students in the both list
print '{} students are in both classes'.format(len(both))