Using for loops with a list of tuples - python

tuplelist = [('John', 'David', 'Roger'), ('Linda', 'Jane', 'Siri')]
counter = 0
for x in tuplelist:
if counter != 0:
print(' likes ' + x[0])
print(x[0], end='')
counter += 1
I'm trying to find a good way to print the following using the list of tuples from the code above:
John likes Linda
David likes Jane
Roger likes Siri
The code above is my current attempt, which only prints "John likes Linda". I haven't found a solution to do this all at once. I could technically copy-paste the code twice and insert x[1] and x[2] in each block respectively. However, I've read that repetitious code is not good practice, so I was hoping some of you could help me in figuring out a more elegant solution.
Thank you very much for your help in advance

You can use build-in function zip
for man, woman in zip(*tuplelist):
print(man, 'likes', woman)

Although I think the answer by Relandom is the better and more pythonic appraoch, I would like to give you a second answer, pursuing the appraoch you tried (and might be easier to understand for beginners):
tuplelist = [('John', 'David', 'Roger'), ('Linda', 'Jane', 'Siri')]
counter = 0
for y in tuplelist[0]:
print(f'{y} likes {tuplelist[1][counter]}')
counter += 1
As you can see, we're still iterating over something. This time not the tuplelist, but the first tuple in this list (the male names). Sticking to your concept of a counter variable within the loop, we use this variable to access the second tuple (tuplelist[1]) in your list and get the respective value (=female name).

Related

How to reference a specific part of a dictionary in Python

Alright, so I am trying to create a simple thing that will tell me the showtimes of the movies at the theatre, the names of the movies, and the Rotten Tomatoes score in Python, but I am having a hard time figuring out how to get the meterScore.
actorCount = 0
actors = []
criticCount = 0
critics = []
franchiseCount = 0
franchises = []
movieCount = 3
movies = [{'name': 'Frozen II', 'year': 2019, 'url': '/m/frozen_ii', 'image': 'https://resizing.flixster.com/QZg2MuPQoRlWcWYAwufbQBlv-I0=/fit-in/80x80/v1.bTsxMzIwMzIxODtqOzE4Mjg3OzEyMDA7NTQwOzgxMA', 'meterClass': 'certified_fresh', 'meterScore': 76, 'castItems': [{'name': 'Kristen Bell', 'url': '/celebrity/kristin_bell'}, {'name': 'Idina Menzel', 'url': '/celebrity/idina_menzel'}, {'name': 'Josh Gad', 'url': '/celebrity/josh_gad'}], 'subline': 'Kristen Bell, Idina Menzel, Josh Gad, '}]
tvCount = 0
tvSeries = []
What I am trying to get from that list of data is the meterScore, if you scroll over to the right far enough you can see it. All this data is part of a bigger dictionary, which I named resultOne, but I don't think that matters. I just need some help figuring out how to reference and get the meterScore from the dictionary, so I can print it out, so when I want to see what movies and what rating they got I can just run this program and it will do it for me. I don't really use dictionaries that much, but the library I am using to get the Rotten Tomato data creates it as this very hard to reference dictionary, so any help is appreciated! What I don't get is that if I try to print(resultOne.movies) it says that that is not an attribute or something to that affect, even though when I put it into something that will print out the keys and values, such as I did to get the code above, it clearly shows it is a key. I also tried to print(resultOne.movies[meterScore]), but that didn't work either.
Dictionary values are looked up by their keys using [], not ..
Now, the trick is that the movies key points to a list. So you need to mix two kinds of indexing that both use []: dictionary indexing, which is by key, and list indexing, which is by position in the list (starting at 0).
Ultimately, you want to do this:
score = resultOne['movies'][0]['meterScore']
^ ^ ^
| | |
lookup in outer dict | |
first item in list |
lookup in inner dict
Try this:
movies[0]['meterScore']
# 76
Why don't you try something like this to extract every meterScore from all the movies in the dictionary:
listOfAllMeterScores = [ movie['meterScore'] for movie in movies ]
In that snippet, movies is a list containing a dict. So index the list then index the dict:
movies[0]['meterScore']
If movies might contain more than one item (or zero for that matter), iterate over it instead to get a list of the meterScores:
meter_scores = [movie['meterScore'] for movie in movies]

Iterate over a list of strings in python

I am trying to set up a data set that checks how often several different names are mentioned in a list of articles. So for each article, I want to know how often nameA, nameB and so forth are mentioned. However, I have troubles with iterating over the list.
My code is the following:
for element in list_of_names:
for i in list_of_articles:
list_of_namecounts = len(re.findall(element, i))
list_of_names = a string with several names [nameA nameB nameC]
list_of_articles = a list with 40.000 strings that are articles
Example of article in list_of_articles:
Index: 1
Type: str
Size: Amsterdam - de financiële ...
the error i get is: expected string or buffer
I though that when iterating over the list of strings, that the re.findall command should work using lists like this, but am also fairly new to Python. Any idea how to solve my issue here?
Thank you!
If your list is ['apple', 'apple', 'banana'] and you want the result: number of apple = 2, then:
from collections import Counter
list_count = Counter(list_of_articles)
for element in list_of_names:
list_of_namecounts = list_count[element]
And assuming list_of_namecounts is a list ¿?
list_of_namecounts = []
for element in list_of_names:
list_of_namecounts.append(list_count[element])
See this for more understanding

Comparing Sets held in a Dictionary in Python

I've got the following which takes multiple lines of user input such as 'English Bob Luke' to store a Set in a Dictionary about which people speak which language. I've used a Dictionary to hold the multiple lines of input to create multiple Sets, but I now need to compare the difference between Sets to see if someone only speaks one language.
languages = {}
while True:
info = input('Line: ').split()
if info != []:
languages[info[0]] = set(info[1:])
else:
break
I can print the sets using the code below, but it doesn't seem to really get me anywhere!
for tongue in languages:
print(set(languages[tongue]))
Totally stuck - any help would be greatly appreciated!
UPDATE
Here in example of what I am trying to achieve:
Line: English Tim Nicky James John Ben
Line: German Nicky Tim Tara
Line: Mandarin Tim John
Line:
James is monolingual.
Tara is monolingual.
Ben is monolingual.
SOLUTION
Completely re-though my approach and ditched the Dictionary! :
english = input("Line: ").split()
en_speakers = set(english[1:len(english)])
multi_speakers = set()
while True:
language = input("Line: ").split()
lan_speakers = language[1:len(language)]
if language == []:
break
else:
multi_speakers |= set(lan_speakers)
monolinguals = en_speakers.difference(multi_speakers)
for person in monolinguals:
print(person, 'is monolingual.')
if multi_speakers == en_speakers:
print ('Everyone is multilingual!')
I'd reverse the order of keys and values in your dictionary, because it makes the problem so much easier. So rather than storing per language the different users that speak it, just create a per user profile of all the languages that person speaks:
from collections import defaultdict
user_langs = defaultdict(list)
while True:
info = map(lambda s: s.strip(), raw_input('Line: ').split())
if info:
for user in info[1:]:
user_langs[user].append(info[0])
else:
break
for user in user_langs:
if len(user_langs[user]) < 2:
print("{} is monolingual.".format(user))
languages[toungue] is already a set, you don't need to set(languages[touge]).
Also you don't need to loop the dictionary you can simply get those set from dictionary by lanuages.values().
Not entirely sure what you want to achieve here though. At a wild guess, you may want the unique value from the languages values?
You can achieve this by updating values to a new set:
Change this:
for tongue in languages:
print(set(languages[tongue]))
To this:
new_set = set()
for v in languages.values():
new_set.update(v)
new_set # dummy lanugages
{'English', 'Japanese', 'whatever', 'yeah'}
Updated
To achieve what you want, you can use Counter and return the key if value == 1.
A more detailed explanation is that, under a for/loop you are going to compare 1 set to another set. But what you actually need,is to compare all sets, so I choose to use c to update all individual set values under a for/loop, and afterward do whatever you want out from that c. I use Counter here as what you want to count if anyone has only got 1 language.
from collections import Counter
c = Counter()
for v in languages.values():
c.update(v)
for k,v in c.iteritems():
if v == 1:
print k, " is monolingual"
Ben is monolingual
James is monolingual
Tara is monolingual
The c looks like this:
c
Counter({'Tim': 3, 'Nicky': 2, 'John': 2, 'Ben': 1, 'James': 1, 'Tara': 1})

Sorting a list of the form [(single value), [(tuple 1), (tuple2), ...], (another value),[...]]

I'm not sure what the best way to write a title for this question is, so sorry for the somewhat poor title. Instead, I'll just write an example.
What I want to do is take the items from a dictionary and place them in a list, (which I have done with the following code).
for key,val in teamDict.items(): teamlist.append((key,val))
Now this list contains info on teams in the NFL, and is stored in the form:
[('DAL', [(2011, 'Chauncey Washington', 47.29080932784636, 1, -1, 0, 0), (2011, 'DeMarco Murray', 90.58014654220617, 164, 897, 2, 1)...]]
And so on, with every team being represented.
Now what I want is for the output to look something like this
Roy Helu 2011 81.33
Ryan Torain 2011 78.16
Tim Hightower 2011 84.20
Andre Brown 2010 50.03
Brandon Banks 2010 69.24
Clinton Portis 2010 108.35
Only for every player from 2011 to be printed after every player from 2010 has been printed. Everything is formatted correctly and printing out correctly, the only trouble I'm running into is not being able to get the years sorted properly. Also here is the code that sorts through the list:
for item in teamlist:
for sub_item in item:
teamName = item[0]
if user_input == teamName:
for sub_sub_item in sub_item:
print(" {:<25} {:^6} {:>8.2f}".format(sub_sub_item[1], sub_sub_item[0], sub_sub_item[2]))
I know about the key = operator.itemgetter() option, but I'm not sure if that would even work for a list like this or where to put it in my for loops.
Any hints to point me in the right direction would be much appreciated.
You can try this:
for item in teamlist:
for sub_item in item:
teamName = item[0]
if user_input == teamName:
sorted_lists = [x for x in zip(*sorted(zip(sub_item), key=lambda x: x[0]))]
for sub_sub_item in sorted_lists[0]:
print(" {:<25} {:^6} {:>8.2f}".format(sub_sub_item[1], sub_sub_item[0], sub_sub_item[2]))
If you are not a big fan of lambda, then you can use operator's itemgetter method which is as:
sorted_lists = [x for x in zip(*sorted(zip(sub_item), key=operator.itemgetter(0)))]
I am not quite certain what you want to sort on, but take a look at the documentation, i.e. https://wiki.python.org/moin/HowTo/Sorting.
You can supply a function to sorted, to determine the key to sort by, so to sort [(2011, 'Chauncey Washington', 47.29080932784636, 1, -1, 0, 0), (2011, 'DeMarco Murray', 90.58014654220617, 164, 897, 2, 1)...] by year you could call
from operator import itemgetter
...
sorted(yourList, key=itemgetter(0))
or with a lambda
sorted(yourList, key= lambda item: item[0] )
For more complex sorts look at the section Sort Stability and Complex Sorts from the link above. Basically you start sorting by the least important keys, and then do stable sorts for the more important sort keys till you reach the most important one.
It looks like the elements within each inner tuple are already in the correct order for sorting (that is, most significant element first), so the simplest is to sort them as you are building teamlist:
for key, val in teamDict.items():
teamlist.append((key, sorted(val)))
This is a simple enough loop that you could make it a list comprehension if you like:
teamlist = [(key, sorted(val)) for key, val in teamDict.items()]

Comparing values in a dictionary

Using Python 3.3
Hi, I'm pretty new to programming/Python, so please don't go into too in-depth/complex methods of solving this problem.
I have a dictionary in which the keys are the person's name, and each of the key's values is a list of the names of the person's friends. For example:
friends_of_person = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}
This dictionary can be longer.
What my question is, how do I write a for loop or code that will loop through the values and compare each of the values to each of the values of another key's values. To make this clearer, let's use the above example. Albus is a friend to Harry, Ron, and Hermione. Harry is a friend to Ron and Hermione.
But I want to compare 'Ron' to the 'Ron', 'Hermione', and 'Neville' from the key Harry.
And then what I want is to see if 'Ron' is a friend of Harry. IF and ONLY if Ron is a friend of Harry, then I want to make 'Harry' as a potential friend of 'Albus'. The case applies to when comparing 'Hermione' to the 'Ron' and 'Hermione' from Harry's values. - this is like mutual friends.
The following is the code I've written, but it didn't seem to yield the correct answer.
friends_of_person = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}
for person in friends_of_person:
friends_list = friends_of_person[person]
for friend in friends_list:
recommendation = ''
for another_person in friends_of_person:
if friend in friends_of_person[another_person]:
recommendation = another_person
It doesn't seem correct. But if anyone can give me hints/tips to put me on the right direction, it'll be greatly appreciated!
Thank you in advance :)
Use set to check the intersection of people's friend list:
In [352]: lst1=friends_of_person['Albus']
In [353]: lst2=friends_of_person['Harry']
In [354]: lst1
Out[354]: ['Ron', 'Hermione']
In [355]: lst2
Out[355]: ['Ron', 'Hermione', 'Neville']
In [356]: set(lst1)&set(lst2)
Out[356]: set(['Hermione', 'Ron'])
If you want approach using only simple iterations and basic features, here you go:
for friend in friends_of_person['Albus']:
recommendation = []
for person, friends in friends_of_person.items():
if person == 'Albus':
continue # we don't need anyone who already is his friend
for potential in friends:
if potential in friends_of_person['Albus'] and potential not in recommendation:
recommendation.append(potential)
print(potential)
...:
Neville
PS. It's ugly, but that's what OP wanted...
#zhangxaochen's answer using sets is in my opinion the neatest. Nonetheless, if you want to use lists you could do something like:
friends = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}
def mutual_friends(a, b):
return [x for x in friends[a] if x in friends[b]]
Note that's re-coding set intersection (EDIT: if you have been instructed not to use set intersection then this solution is good since you code it yourself :)).
So
def recommendations(x):
result = []
for f in friends.keys():
if f != x and mutual_friends(x, f) > 1:
result.append(f)
return result
Basically, for a given person x, find all the people that have more than one mutual friend with them. You could change it to == 2 if you want exactly 2 mutual friends.

Categories

Resources