Python Forum
Homework - List containing tuples containing dicti - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Homework - List containing tuples containing dicti (/thread-35869.html)



Homework - List containing tuples containing dicti - Men - Dec-25-2021

Hi guys...I'm baaaaack!

I have a list that contains listed tuples and inside of each tuple there is a dictionary.

I have to access the dictionaries and get the 'last_name' from all the records and use the Counter() function to return the number of occurrences for each last name. Where the output for example would be 'doe': 2, 'stark': 1 etc...

I have a result that works but for some reason when I define a function and add the code it gives me a totally different response.

Here we go....oh and one more thing...below is used to get the results from the function:

result = get_last_name_count(buckets)
for k, v in result.items():
print(f"{k}: {v}")

from collections import Counter

buckets = [ ('[email protected]',{'first_name':'john','last_name':'doe'}),
            ('[email protected]',{'first_name':'jane','last_name':'doe'}),
            ('[email protected]',{'first_name':'derek','last_name':'zoolander'}),
            ('[email protected]',{'first_name':'murph','last_name':'cooper'}),
            ('[email protected]',{'first_name':'ned','last_name':'stark'})
            ]

final_list = []
for key, value in buckets:
    last_names = value['last_name']
    final_list.append(last_names)

print(Counter(final_list))

""" When I run the print within the for loop, I get the following output: """
# {'doe': 1}
# {'doe': 2}
# {'doe': 2, 'zoolander': 1}
# {'doe': 2, 'zoolander': 1, 'cooper': 1}
# {'doe': 2, 'zoolander': 1, 'cooper': 1, 'stark': 1}
""" The last one is the one I need """

""" When I run the print outside of the for loop, I get the following output: """
# Counter({'doe': 2, 'zoolander': 1, 'cooper': 1, 'stark': 1})

""" Here's the function """
def get_last_name_count(list_of_records):
    final_list = []
    for key, value in buckets:
         last_names = value['last_name']
         final_list.append(last_names)
         return Counter(final_list)

""" When I return the Counter in/out the function, I get the following output: """
# in I get: doe: 1
# out I get: 
# doe: 2
# zoolander: 1
# cooper: 1
# stark: 1



RE: Homework - List containing tuples containing dicti - BashBedlam - Dec-25-2021

You just havereturn Counter(final_list)indented one tab too far. It's returning after just one iteration through the loop.
from collections import Counter
 
buckets = [ ('[email protected]',{'first_name':'john','last_name':'doe'}),
			('[email protected]',{'first_name':'jane','last_name':'doe'}),
			('[email protected]',{'first_name':'derek','last_name':'zoolander'}),
			('[email protected]',{'first_name':'murph','last_name':'cooper'}),
			('[email protected]',{'first_name':'ned','last_name':'stark'})
			]
 
def get_last_name_count(list_of_records):
	final_list = []
	for key, value in list_of_records:
		 last_names = value['last_name']
		 final_list.append(last_names)
	return Counter(final_list)
 
result = get_last_name_count(buckets)
for k, v in result.items():
	print(f"{k}: {v}")
Output:
doe: 2 zoolander: 1 cooper: 1 stark: 1



RE: Homework - List containing tuples containing dicti - Men - Dec-25-2021

Geez man, You mean to tell me that I had this thing right the whole time!! Wall .

I actually thought that it was supposed to come out horizontally instead of vertically and since it wasn't coming out that way, I thought that it was wrong.

Thanks again Bash...you're a life saver.

Cheers,


RE: Homework - List containing tuples containing dicti - perfringo - Dec-25-2021

I think that there are several things that could be improved.

Naming: there is no key, value in tuple and therefore such naming is misleading (this tuple actually has string and dictionary in it). If you want to unpack the tuple then give meaningful names, in this case it could be for email, record in data:

No need to build separate/temporary list: Counter plays nicely with other parts of Python so one can feed generator or list comprehension directly to it.

So alternatively it can be written as:

from collections import Counter

data = [('[email protected]',{'first_name':'john','last_name':'doe'}),
        ('[email protected]',{'first_name':'jane','last_name':'doe'}),
        ('[email protected]',{'first_name':'derek','last_name':'zoolander'}),
        ('[email protected]',{'first_name':'murph','last_name':'cooper'}),
        ('[email protected]',{'first_name':'ned','last_name':'stark'})]

last_names = Counter(row[1]['last_name'] for row in data)
print(*(f'{k}: {v}' for k, v in last_names.items()), sep='\n')
Output:
doe: 2 zoolander: 1 cooper: 1 stark: 1



RE: Homework - List containing tuples containing dicti - Men - Dec-28-2021

Hi perfringo,

I acknowledge all your criticisms. However, do understand that:

1. This was an exercise provided to me by an instructor and my only task was to find my way out.
2. I'm still learning...perfection is gained with time.

With all the variations of coding this one program I understand the logic in all of them but I haven't reached that level yet. Additionally yours is the simplest so far. I do pray to reach your level of experience/expertise.

Cheers,


(Dec-25-2021, 09:05 AM)perfringo Wrote: I think that there are several things that could be improved.

Naming: there is no key, value in tuple and therefore such naming is misleading (this tuple actually has string and dictionary in it). If you want to unpack the tuple then give meaningful names, in this case it could be for email, record in data:

No need to build separate/temporary list: Counter plays nicely with other parts of Python so one can feed generator or list comprehension directly to it.

So alternatively it can be written as:

from collections import Counter

data = [('[email protected]',{'first_name':'john','last_name':'doe'}),
        ('[email protected]',{'first_name':'jane','last_name':'doe'}),
        ('[email protected]',{'first_name':'derek','last_name':'zoolander'}),
        ('[email protected]',{'first_name':'murph','last_name':'cooper'}),
        ('[email protected]',{'first_name':'ned','last_name':'stark'})]

last_names = Counter(row[1]['last_name'] for row in data)
print(*(f'{k}: {v}' for k, v in last_names.items()), sep='\n')
Output:
doe: 2 zoolander: 1 cooper: 1 stark: 1