Skip to content

Instantly share code, notes, and snippets.

@abir-taheer
Last active June 12, 2023 21:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abir-taheer/57e9170cdc7c71f164d3a9136d085d21 to your computer and use it in GitHub Desktop.
Save abir-taheer/57e9170cdc7c71f164d3a9136d085d21 to your computer and use it in GitHub Desktop.
Explanation of SO answer for Emperor Wafi
sortedrows = {
# k: v were replaced with key and value, respectively to make it easier to follow
key: value
# enumerate through the sorted
for key, value in sorted(
rownums.items(),
key=lambda item: item[0]
)
}
# okay we have to realize that this is actually just a for loop
# We're going through all of the items after they've been sorted and assigning them as key: value in the object
# first let's take a look at the sorted() function because we're iterating through whatever it returns
# rownums.items() returns an array of tuples
# imagine the following:
rownums = { "a": 3, "b": 2, "c": 3 }
# if we call rownums.items() we get the following:
[('a', 3), ('b', 2), ('c', 1)]
# So now let's look at the second parameter to the sorted() function:
# the 'key' parameter takes in a function
# For every item in the first paramter (our unsorted array) (our unsorted array is an array of tuples)
# It is an array of tuples because that's what rownums.items() returned
# the lambda keyword is used to define functions
lambda item: item[0]
# is the same as
def key_function(item):
return item[0]
#
# What does the function return?
# Essentially a 'key' is like a comparison score we are giving that item
# An item with a key of 1 is placed higher in the dict than an item with a key of 2
# An item with a key of 'a' is placed before an item with a key of 'b'
# Two items with the same key are treated as having the same sort value
# okay so now let's put that together
sorted(
rownums.items(),
# since the item is a tuple, item[0] is the key and item[1] is the value
key=lambda item: item[0]
)
# We are returning item[0] as the 'key' so we are essentially asking it to order it based on keys
# after the sorted function finishes it returns an array that looks like this:
[('a', 3), ('b', 2), ('c', 1)]
# We then iterate through the array in our for loop to recreate the dictionary object
sortedrows = {
key: value for key, value in [('a', 3), ('b', 2), ('c', 1)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment