Reputation: 81
I have a list of tuples that is composed of a string and a dictionary like the following
List = [
("mike", {
'age': 27,
'favorite food': 'pizza',
'favorite drink': 'beer'
}),
("jessie", {
'age': 35,
'favorite food': 'eggs',
'favorite drink': 'tea'
}),
("frank", {
'age': 14,
'favorite food': 'bread',
'favorite drink':'fanta'
})
]
I would like to loop through that list and extract the data in the [favorite drink] in order to compare it with another.
Lets say I loop through the list and check if user likes beer, he gets a score of 1.
so far I've gotten :
for x in list:
if list[0][1] == 'beer':
beer-counter += 1
The problem is I'm only accessing the dictionary, not the element of the dictionary with what I have.
Upvotes: 1
Views: 1317
Reputation: 33724
You'll need to fix up your loop a bit and use a collections.Counter
for easy tally keeping:
lst = [("mike", {'age': 27, 'favorite food': 'pizza', 'favorite drink':'beer'}), ("jessie", {'age': 35, 'favorite food': 'eggs','favorite drink':'tea'}), ("frank", {'age': 14, 'favorite food':'bread', 'favorite drink':'fanta'})]
from collections import Counter
cnt = Counter()
for x in lst:
cnt[x[1]['favorite drink']] += 1
Upvotes: 1
Reputation: 1251
First of all you are missing ending quote '
in your sample data.
this is one of the correct way to accomplish your task.
beer_counter = 0
for x in list:
if x[1]['favorite drink'] == 'beer':
beer_counter += 1
Upvotes: 2
Reputation: 9062
Indeed, list[0][1]
is a dictionary. But if it is a dictionary, you can use the []
operator to get the key you want list[0][1]['favorite drink']
.
Upvotes: 3