简体   繁体   中英

Creating a list from a dictionary

I'm trying to teach myself python so I apologize if the question itself doesn't make much sense.

I am doing the examples of an online introductory to Python course I am sitting in on and the prompt is to write a code to read through a file and find all emails before adding them to a dictionary before printing out the person who had sent the most emails and the number they sent. My issue is that the prompt specifically asks for this to be done by sorting through the list in reverse order.

I managed to get the same end result simply by parsing out the names and then counting each time it popped up before finding the largest value and printing that out with the corresponding key in a for loop. However I was unsure if this is what I was supposed to do or if the book was asking for something else. Does the dictionary itself count as a list?

for k,v in di.items():
   if largest_so_far ==-1
      largest_so_far = v
   elif v > largest_so_far :
      largest_so_far = v
      the_word = k

print(the_word,largest_so_far)

This is the code I used to print out the person with name emails. I tried changing

for k,v in di.items():

into

for k,v in reversed(di.items()):

in order to try and at least get some semblance of printing it out in reversed order but the code ran normally with no changes or issues.

Again, I apologize if this doesn't make much sense. I am almost entirely self taught(only able to watch prerecorded videos and read the text book) and am still trying to attain even a basic understanding of this language.

The for loop as written will always end up with whatever it finds to be the largest v in the dictionary. As such reversed(...) just changes the order in which it checks all the elements of the dictionary, but usually won't change what you see in the print() statement.

Putting a statement inside the for loop might help your debugging, eg print(word, largest_so_far) immediately after the elif block and indented at exactly the same level as the elif .

(I assume you have a statement largest_so_far = -1 prior to the for loop. Consider changing it to largest_so_far = None and then use if not largest_so_far: within the for loop.)

If I understand correctly, what you're really asking is why the book says to sort a list and get the last element (ie max element) instead of just finding the max element. If that's correct, then your way to do it is actually better. It's wasteful to sort a list when all you need is the largest element. This is not a big problem for small datasets (less than, say, 10000 items), but for larger datasets, it would start to get noticeable. This is because finding the largest element just requires looping once, which in big-O notation is O(n) , while sorting requires looping at least once and possibly doubling back a few times, meaning its worst-case performance is O(n log n) , which is worse than O(n) by a bit.*


By the way, if you want to consider a more advanced tool to do the same job, you can use max() with a key function :

max(di.items(), key=lambda kv: kv[1])

Or for keeping a dict of items-to-occurrences, you could use a Counter , which has some handy methods built in like most_common() .


* Implementation detail for CPython : max() actually is slower than list.sort() due to the overhead of the iterator protocol . There's no special case for dict_items or other native data types. (Reference: source code (current tip of master branch) .) To see an actual performance difference, you'd want to look at types that don't have a built-in .sort() method, or types implemented in C with a built-in .max() method like NumPy's ndarray .

İf you want to sort values from higher to lower you can this method:

sorted_list = sorted(di.values(), reverse = True)

In this way you can get list of sorted dictionary values

Then you can use values as you want. Good luck:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM