0
  counts = defaultdict(int)
  for currChar in records['ABC'].values():
      counts[currChar] += 1
  ks = [ct for k,  ct in sorted(counts.items(), key=lambda x: x[1], reverse=True)]

Here I am not following the last line:

1) ct for k

What does this mean? What does k stand for? This is also the first use of variable ct and k in the code. Does ct represent count? What does k represent?

2) ct in sorted(counts.items(), key=lambda x: x[1], reverse=True) What is the meaning of above syntax especially key=lambda x: x[1] Again the code has not declared x variable anywhere in the codebase before its use here.

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 4
    `ct for k` doesn't mean anything; you are parsing it wrong. This is a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions), where `ct` is an expression providing a value for each element of the new list, and `for k, ct in sorted(...)` is the iteration performed over one sequence in order to build the list. – chepner Oct 18 '19 at 13:38
  • As for `lambda`, [consult the tutorial](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions); *it* defines `x`. – chepner Oct 18 '19 at 13:39
  • "Again the code has not declared x variable anywhere in the codebase before its use here" Python *doesn't have* variable declarations. – juanpa.arrivillaga Oct 18 '19 at 13:44
  • Note, this code can be replaced by the single line `ks = Counter(records['ABC'].values()).most_common()` if instead of using a `defaultdict` you import `from collections import Counter` instead. I actually find this one-liner more readable, since it pretty much tells you what it is doing. – juanpa.arrivillaga Oct 18 '19 at 13:47

1 Answers1

1

It is a so-called list-comprehension.

ks = [ct for k,  ct in sorted(counts.items(), key=lambda x: x[1], reverse=True)]

is the same as:

ks = []
for k,  ct in sorted(counts.items(), key=lambda x: x[1], reverse=True):
    ks.append(ct)
ks = [ct for k,  ct in sorted(counts.items(), key=lambda x: x[1], reverse=True)]
*1    *2     *3        *4            *5       *6                  *7

 1. list that is created by the list comprehension
 2. expression of the elements of the new list
 3. Key(k) and value(ct) of the item that is currently iterated
 4. sorts the output
 5. List-comprehension iterates over items of dictionary counts. each step looks like (key, value). they are extracted by k, ct
 6. Sorts by value instead of key (default)
 7. Sorts reversed

You could write it shorter because the key isn't used

ks = []
for ct in sorted(counts.values(), reverse=True):
    ks.append(ct)
Frank
  • 1,959
  • 12
  • 27