Dec-25-2021, 12:31 AM
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}")
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}")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from collections import Counter buckets = [ ( 'john.doe@example.com' ,{ 'first_name' : 'john' , 'last_name' : 'doe' }), ( 'jane.doe@example.com' ,{ 'first_name' : 'jane' , 'last_name' : 'doe' }), ( 'derek.zoo@example.com' ,{ 'first_name' : 'derek' , 'last_name' : 'zoolander' }), ( 'murph.cooper@example.com' ,{ 'first_name' : 'murph' , 'last_name' : 'cooper' }), ( 'ned.stark@example.com' ,{ '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 |