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'
)
Related
For some reason .index and .find is not working in my program.
Basically, I want the program to find the index number of the list with the set criteria.
For example this list:
['Synonyms: Pocket Monsters, Indigo League, Adventures on the Orange Islands, The Johto Journeys, Johto League Champions, Master Quest', 'Japanese: ポケットモンスター', 'Type: TV', 'Episodes: 276', 'Status: Finished Airing', 'Aired: Apr 1, 1997 to Nov 14, 2002', 'Premiered: Spring 1997', 'Broadcast: Thursdays at 19:00 (JST)', 'Producers: TV Tokyo, TV Tokyo Music, Studio Jack', 'Licensors: VIZ Media, 4Kids Entertainment', 'Studios: OLM', 'Source: Game', 'Genres: Action, Adventure, Comedy, Kids, Fantasy', 'Duration: 24 min. per ep.', 'Rating: PG - Children', 'Score: 7.341 (scored by 291,570 users)', 'Ranked: #21572', 'Popularity: #287', 'Members: 504,076', 'Favorites: 4,076', '']
I would like to find the index number of the position of "Genres". I tried doing it .index("Genres:") but that didn't find the index number and returned an error.
I need this to find the index number because, for other pages on this website, the "genre" is in a different position
This is what I tried and just returned an error
GIndex = Information.index("Genres")
print (Information[GIndex])
Genre = (Information[GIndex])
You could also use a list comprehension:
word = 'Genres'
results = [i for i, l in enumerate(lst) if word in l]
for index to work it would need to be an exact match. This will check if 'Genres' is contained within any string in the list and print its index
word = 'Genres'
for i, item in enumerate(lst):
if word in item:
print(i, item)
you can easily turn this into a function to return i which is the index
ou can use enumerate()
l=['Synonyms: Pocket Monsters, Indigo League, Adventures on the Orange Islands, The Johto Journeys, Johto League Champions, Master Quest', 'Japanese: ポケットモンスター', 'Type: TV', 'Episodes: 276', 'Status: Finished Airing', 'Aired: Apr 1, 1997 to Nov 14, 2002', 'Premiered: Spring 1997', 'Broadcast: Thursdays at 19:00 (JST)', 'Producers: TV Tokyo, TV Tokyo Music, Studio Jack', 'Licensors: VIZ Media, 4Kids Entertainment', 'Studios: OLM', 'Source: Game', 'Genres: Action, Adventure, Comedy, Kids, Fantasy', 'Duration: 24 min. per ep.', 'Rating: PG - Children', 'Score: 7.341 (scored by 291,570 users)', 'Ranked: #21572', 'Popularity: #287', 'Members: 504,076', 'Favorites: 4,076', '']
for i, s in enumerate(l):
if "Genres" in s:
print(i)
>>>12
In your list there is not element whose value is "Genres". "Genres" and "Genres: Action, Adventure, Comedy, Kids, Fantasy" are not equal. If you want to find the element which starts with "Genres", you can write a very simple for loop like
for index, item in enumerate(information_list):
if item.startswith('Genres'):
print(index, item)
break
A better way would be like #9769953 suggested is to use a dictionary. The efficiency of lookup in dict is pretty much constant time and your data will be organized neatly with keys corresponding to property name and value corresponding to property value.
A dictionary would look like this
information_dict = {
"Synonyms": "Pocket Monsters, Indigo League, Adventures on the Orange Islands, The Johto Journeys, Johto League Champions, Master Quest",
"Japanese": "ポケットモンスター",
"Type": "TV",
"Episodes": "276",
"Status": "Finished Airing",
"Aired": "Apr 1, 1997 to Nov 14, 2002",
"Premiered": "Spring 1997",
"Broadcast": "Thursdays at 19:00 (JST)",
"Producers": "TV Tokyo, TV Tokyo Music, Studio Jack",
"Licensors": "VIZ Media, 4Kids Entertainment",
"Studios": "OLM",
"Source": "Game",
"Genres": "Action, Adventure, Comedy, Kids, Fantasy",
"Duration": "24 min. per ep.",
"Rating": "PG - Children",
"Score": "7.341 (scored by 291,570 users)",
"Ranked": "#21572",
"Popularity": "#287",
"Members": "504,076",
"Favorites": "4,076"
}
And by doing information_dict["Genres"] you can get the value "Action, Adventure, Comedy, Kids, Fantasy".
hello guys so i have this notepad containing country and capital list.
then i want to make input of the country name to reveal the capital so this is where i get confused.
country.txt
malaysia, vietnam, myanmar, china, sri lanka, japan, brazil, usa, australia, thailand, russia, uk
kuala lumpur, hanoi, yangon, beijing, colombo, tokyo, rio, washington, canberra, bangkok, moscow, london
thats the notepad file for the country and capital
f = open(r'C:\Users\User\Desktop\country.txt')
count = 0
for line in f:
line = line.rstrip('\n')
rec = line.split(',')
count = count + 1
ctry = input('\nEnter country name: ')
ctry = ctry.lower()
for i in country:
if ctry == country[i]:
print ('country:', ctry)
print ('capital:', capital[i])
break
else:
print ('country not in the list')
here is where i don't know what to do to make it work.
i want the output to be like
Enter country name: vietnam
Country: vietnam
Capital: hanoi
and when there's no country on the list
Enter country name: france
Country not in the list
First of all, here are some reasons why your code isn't working and some suggestions too:
You didn't define the variables country or capital, so you were comparing the input with nothing, this will raise an error because the variable wasn't defined.
If you open a file, you should close it after manipulate it, as suggestion it's better to use with.
Please, see this about how for loops works, because you were trying to index country[i], knowing that i is an element not an integer index.
Nonethless, you could try this:
with open(r'C:/Users/User/Desktop/country.txt') as f:
lines=f.read().splitlines()
countries=lines[0].strip().split(', ')
cities=lines[1].strip().split(', ')
count = 0
print(countries)
print(cities)
ctry = input('\nEnter country name: ')
ctry = ctry.lower()
for i in countries:
if i == ctry:
print ('country:', ctry)
print ('capital:', cities[countries.index(i)])
break
else:
print ('country not in the list')
Output:
countries
>>>['malaysia', 'vietnam', 'myanmar', 'china', 'sri lanka', 'japan', 'brazil', 'usa', 'australia', 'thailand', 'russia', 'uk']
cities
>>>['kuala lumpur', 'hanoi', 'yangon', 'beijing', 'colombo', 'tokyo', 'rio', 'washington', 'canberra', 'bangkok', 'moscow', 'london']
>>>'\nEnter country name: ' uk
>>>country: uk
>>>capital: london
I'm writing a program using dictionaries nested within a list. I want to print the name of each dictionary when looping through the list, but don't know how to do that without calling the entire contents of the dictionary. Here is my code:
sam = {
'food' : 'tortas',
'country' : 'mexico',
'song' : 'Dream On',
}
dave = {
'food' : 'spaghetti',
'country' : 'USA',
'song' : 'Sweet Home Alabama',
}
people = [sam, dave]
for person in people:
for key, value in sorted(person.items()):
print( #person's name +
"'s favorite " + key + " is " + value + ".")
Here is the output:
's favorite country is mexico.
's favorite food is tortas.
's favorite song is Dream On.
's favorite country is USA.
's favorite food is spaghetti.
's favorite song is Sweet Home Alabama.
Everything works, I just need the names of my dictionaries to print. What's the solution?
The (more) correct way of doing this is to construct a dict of dicts instead, such as:
people = {'sam': {'food' : 'tortas',
'country' : 'mexico',
'song' : 'Dream On',
},
'dave': {'food' : 'spaghetti',
'country' : 'USA',
'song' : 'Sweet Home Alabama',
}
}
Then you can simply do the following:
for name, person in people.items():
for key, value in sorted(person.items()):
print(name + "'s favorite " + key + " is " + value + ".")
This will print the following:
dave's favorite country is USA.
dave's favorite food is spaghetti.
dave's favorite song is Sweet Home Alabama.
sam's favorite country is mexico.
sam's favorite food is tortas.
sam's favorite song is Dream On.
As a side note, it is more readable to use string formatting in your print statement:
print("{0}'s favorite {1} is {2}".format(name, key, value))
what you are basically trying to do is printing the name of a variable. Of course, this is not reccomended. If you really want to do this, you should take a look at this post:
How can you print a variable name in python?
What i would do, is to store the name of the dictionary inside of the lists. You could do this by changing 'people = [sam, dave]' to 'people = [["sam", sam], ["dave", dave]]'. This way, person[0] is the name of the person, and person[1] contains the information.
The simplest way is to store the name as a string that maps to the matching variable identifier:
people = {'sam':sam, 'dave':dave}
for name, person in people.items():
for key, value in sorted(person.items()):
print(name + "'s favorite " + key + " is " + value + ".")
If you really don't like the idea of typing each name twice, you could 'inline' the dictionaries:
people = {
'sam':{
'food' : 'tortas',
'country' : 'mexico',
'song' : 'Dream On',
},
'dave':{
'food' : 'spaghetti',
'country' : 'USA',
'song' : 'Sweet Home Alabama',
}
}
Finally, if you can rely on those variables being in the global namespace and are more concerned with just making it work than purity of practice, you can find them this way:
people = ['sam', 'dave']
for name in people:
person = globals()[name]
for key, value in sorted(person.items()):
print(name + "'s favorite " + key + " is " + value + ".")
Values in a list aren't really variables any more. They aren't referred to by a name in some namespace, but by an integer indicating their offsets from the front of the list (0, 1, ...).
If you want to associate each dict of data with some name, you have to do it explicitly. There are two general options, depending on what's responsible for tracking the name: the collection of people, or each person in the collection.
The first and easiest is the collections.OrderedDict --- unlike the normal dict, it will preserve the order of the people in your list.
from collections import OrderedDict
sam = {
'food': 'tortas',
'country': 'Mexico',
'song': 'Dream On',
}
dave = {
'food': 'spaghetti',
'country': 'USA',
'song': 'Sweet Home Alabama',
}
# The OrderedDict stores each person's name.
people = OrderedDict([('Sam', sam), ('Dave', dave)])
for name, data in people.items():
# Name is a key in the OrderedDict.
print('Name: ' + name)
for key, value in sorted(data.items()):
print(' {0}: {1}'.format(key.title(), value))
Alternatively, you can store each person's name in his or her own dict... assuming you're allowed to change the contents of those dictionaries. (Also, you wouldn't want to add anything to the data dictionary that would require you to change / update the data more than you already do. Since most people change their favorite food or song much more often than they change their name, this is probably safe.)
sam = {
# Each dict has a new key: 'name'.
'name': 'Sam',
'food': 'tortas',
'country': 'Mexico',
'song': 'Dream On',
}
dave = {
'name': 'Dave',
'food': 'spaghetti',
'country': 'USA',
'song': 'Sweet Home Alabama',
}
people = [sam, dave]
for data in people:
# Name is a value in the dict.
print('Name: ' + data['name'])
for key, value in sorted(data.items()):
# Have to avoid printing the name again.
if 'name' != key:
print(' {0}: {1}'.format(key.title(), value))
Note that how you print the data depends on whether you store the name in the collection (OrderedDict variant), or in each person's dict (list variant).
Thanks for the great input. This program is for a practice example in "Python Crash Course" by Eric Matthes, so the inefficient "dictionaries inside list" format is intentional. That said, I got a lot out of your comments, and altered my code to get the desired output:
sam = {
#Added a 'name' key-value pair.
'name' : 'sam',
'food' : 'tortas',
'country' : 'mexico',
'song' : 'Dream On',
}
dave = {
'name' : 'dave',
'food' : 'spaghetti',
'country' : 'USA',
'song' : 'Sweet Home Alabama',
}
people = [sam, dave]
for person in people:
for key, value in sorted(person.items()):
#Added if statement to prevent printing the name.
if key != 'name':
print(person['name'].title() + "'s favorite " + key + " is " + value + ".")
#Added a blank line at the end of each for loop.
print('\n')
Here is the output:
Sam's favorite country is mexico.
Sam's favorite food is tortas.
Sam's favorite song is Dream On.
Dave's favorite country is USA.
Dave's favorite food is spaghetti.
Dave's favorite song is Sweet Home Alabama.
Thanks again, all who provided insightful answers.
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']
)
I have a text file with the details of a set of restaurants given one after the other. The details are name, rating, price and type of cuisines of a particular restaurant. The contents of text file is as given below.
George Porgie
87%
$$$
Canadian, Pub Food
Queen St. Cafe
82%
$
Malaysian, Thai
Dumpling R Us
71%
$
Chinese
Mexican Grill
85%
$$
Mexican
Deep Fried Everything
52%
$
Pub Food
I want to create a set of dictionaries as given below:
Restaurant name to rating:
# dict of {str : int}
name_to_rating = {'George Porgie' : 87,
'Queen St. Cafe' : 82,
'Dumpling R Us' : 71,
'Mexican Grill' : 85,
'Deep Fried Everything' : 52}
Price to list of restaurant names:
# dict of {str : list of str }
price_to_names = {'$' : ['Queen St. Cafe', 'Dumpling R Us', 'Deep Fried Everything'],
'$$' : ['Mexican Grill'],
'$$$' : ['George Porgie'],
'$$$$' : [ ]}
Cuisine to list of restaurant name:
#dic of {str : list of str }
cuisine_to_names = {'Canadian' : ['George Porgie'],
'Pub Food' : ['George Porgie', 'Deep Fried Everything'],
'Malaysian' : ['Queen St. Cafe'],
'Thai' : ['Queen St. Cafe'],
'Chinese' : ['Dumpling R Us'],
'Mexican' : ['Mexican Grill']}
What is the best way in Python to populate the above dictionaries ?
Initialise some containers:
name_to_rating = {}
price_to_names = collections.defaultdict(list)
cuisine_to_names = collections.defaultdict(list)
Read your file into a temporary string:
with open('/path/to/your/file.txt') as f:
spam = f.read().strip()
Assuming the structure is consistent (i.e. chunks of 4 lines separated by double newlines), iterate through the chunks and populate your containers:
restraunts = [chunk.split('\n') for chunk in spam.split('\n\n')]
for name, rating, price, cuisines in restraunts:
name_to_rating[name] = rating
# etc ..
for the main reading loop, you can use enumerate and modulo to know what is the data on a line:
for lineNb, line in enumerate(data.splitlines()):
print lineNb, lineNb%4, line
for the price_to_names and cuisine_to_names dictionnaries, you could use a defaultdict:
from collections import defaultdict
price_to_names = defaultdict(list)