<p>Just make sure to cast the count to an integer prior to sorting. Assuming you need to do something with the counts, you could use:</p>
<pre><code>import csv

from operator import itemgetter
from pprint import pprint


with open(&quot;6mers.tsv&quot;) as kmer_file:

    reader = csv.reader(kmer_file, delimiter=&quot;\t&quot;)
    counts = ((kmer, int(count)) for kmer, count in reader)

    sorted_kmers = sorted(counts, key=itemgetter(1), reverse=True)

    pprint(sorted_kmers)
</code></pre>
<p>Results:</p>
<pre><code>[('TTCCAA', 13),
 ('TTGAAA', 6),
 ('TTTAAA', 6),
 ('TGGTAA', 5),
 ('TGTCAA', 5),
 ('TTGCAA', 4),
 ('TGCCAA', 2),
 ('TGGACA', 2),
 ('TGGGAA', 2),
 ('TGTGAA', 2)]
</code></pre>

CC BY-SA 4.0
2023-02-01T21:21:06.203Z
This works! Thank you!
rimo
CC BY-SA 4.0
2023-02-01T00:22:31.807Z
2023-02-01T00:22:31.807Z
Steve
<p>This is untested code ... without seeing to the raw file its tricky.
Could you try:</p>
<pre><code>import csv
with open(&quot;6mers.tsv&quot;) as kmer_file:
    tsv_reader = csv.DictReader(kmer_file, delimiter=&quot;\t&quot;)
    mydict = {rows[0]:rows[1] for rows in tsv_reader if not rows[0] == 'kmer'}

sorted_kmers = sorted(mydict.items(), key=lambda x:x[1], reverse=True)
print(sorted_kmers)
</code></pre>
<p>I'm assuming there is a header called 'kmer'</p>
<hr />
<p>The output didn't work. The rows['kmers'] infers that (somehow) tsv_reader is already a dictionary (that's not how I thought it worked). Thus try,</p>
<pre><code>import csv
with open(&quot;6mers.tsv&quot;) as kmer_file:
    tsv_reader = csv.DictReader(kmer_file, delimiter=&quot;\t&quot;)
    mydict = {rows['kmers']:rows['count'] for rows in tsv_reader}

sorted_kmers = sorted(mydict.items(), key=lambda x:x[1], reverse=True)
print(sorted_kmers)
</code></pre>
<p>Unless it's loaded as a singular dictionary with Kmer as the key and count as the value the sort line will not work. Once that format is achieved as a dictionary then it will work.</p>
<p>What I don't understand is where it's getting 'kmer' or 'count' from if there are no headers in the csv file. Something isn't right if the above code works.</p>

CC BY-SA 4.0
2023-01-31T21:23:40.800Z
I tried the code you wrote but I got this error message: Traceback (most recent call last):

  File ~/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File ~/Desktop/new_try/untitled1.py:12
    mydict = {rows[0]:rows[1] for rows in tsv_reader}

  File ~/Desktop/new_try/untitled1.py:12 in <dictcomp>
    mydict = {rows[0]:rows[1] for rows in tsv_reader}

KeyError: 0
rimo
CC BY-SA 4.0
2023-01-31T21:24:17.527Z
There was a header that I manually added with "kmer" and "count" but the raw result file from KMC does not include that header so I want to try and do it without the header added in
rimo
CC BY-SA 4.0
2023-01-31T21:46:10.513Z
I don't know why it's not working! It's so strange. I tried a different IDE just to make sure there wasn't a a bug with the one I was using but it really isn't working with either of them...
rimo
CC BY-SA 4.0
2023-01-31T21:48:35.410Z
does "rows[0]" look for a specific instance of 0 in the keys?
rimo
CC BY-SA 4.0
2023-02-01T00:21:20.233Z
@rimo what I think is happening is `csv` is automatically placing each column into a dictionary. Fine, I only use it to write out. What I don't understand is where the information for each column which is passed into the dictionary is being stored  - it could only be in the `tsv` file.
M__
CC BY-SA 4.0
2023-02-01T00:22:46.730Z
The reason I'm not up to date is I'd always open `csv` into `pandas`
M__
CC BY-SA 4.0
2023-02-01T00:24:23.503Z
@M__ You can just pass in a list of fieldnames, e.g. `csv.DictReader(kmer_file, fieldnames=['kmer', 'count'], delimiter="\t")`
Steve
CC BY-SA 4.0
2023-02-01T02:25:56.090Z
@Steve Understand entirely, but the code in the questions doesn't carry any fieldnames, unless it is not the precise code that the OP is using.
M__
CC BY-SA 4.0
2023-02-01T21:17:30.583Z
This works except it orders them like this: 9, 8, 7, 66, 63, 6, 59, 55, 5, 4, 32, 3, 22, 2, 13, 12, 10, 1...is there a way to sort them by digits as well?
rimo
CC BY-SA 4.0
2023-02-01T21:51:25.363Z
@rimo interesting it kind of works. The `sort` `lambda` isn't working however: the exact code you used I use all the time for sorting dictionaries using their value.
M__
CC BY-SA 4.0
2023-01-31T21:17:55.077Z
2023-01-31T21:54:40.403Z
2023-01-31T21:54:40.403Z
M__
<p>Hi I am looking to sort a list of kmers into descending order. I used KMC to obtain a list of kmers from a fastq file separated by tab (e.g.; kmer count). From there I have written this python script to attempt to sort the kmers and their counts in descending order:</p>
<pre><code>import csv

with open(&quot;6mers.tsv&quot;) as kmer_file:
    
    tsv_reader = csv.DictReader(kmer_file, delimiter=&quot;\t&quot;)
    
    for kmer in tsv_reader:
        
        name = kmer[&quot;kmer&quot;]
        
        count = kmer[&quot;count&quot;]
        
        # section below attempts to sort the dictionary into descending order
        # taken from (https://www.freecodecamp.org/news/sort-dictionary-by-value-in-python/) 
        sorted_kmers = sorted(kmer.items(), key=lambda x:x[1], reverse=True)

        converted_dict = dict(sorted_kmers)
    
        print(converted_dict)
</code></pre>
<p>The code above outputs this:</p>
<pre><code>{'kmer': 'TGCCAA', 'count': '2'}
{'kmer': 'TGGACA', 'count': '2'}
{'kmer': 'TGGGAA', 'count': '2'}
{'kmer': 'TGGTAA', 'count': '5'}
{'kmer': 'TGTCAA', 'count': '5'}
{'kmer': 'TGTGAA', 'count': '2'}
{'kmer': 'TTCCAA', 'count': '13'}
{'kmer': 'TTGAAA', 'count': '6'}
{'kmer': 'TTGCAA', 'count': '4'}
{'kmer': 'TTTAAA', 'count': '6'}
</code></pre>
<p>Clearly I am creating a separate dictionary for each kmer and it's count - I'm not sure how but I would like a result that looks more like this:</p>
<pre><code>{'TTCCAA', '13'}
{'TTGAAA', '6'}
{'TTTAAA', '6'}
{'TGGTAA', '5'}
{'TGTCAA', '5'}
{'TTGCAA', '4'}
{'TGCCAA', '2'}
{'TGGACA', '2'}
{'TGGGAA', '2'}
{'TGTGAA', '2'}
</code></pre>
<p>Can someone help me fix my code so it works?</p>
<p><strong>EDIT:</strong></p>
<p>The .tsv file looks just like this:</p>
<pre><code>TGCCAA  2
TGGACA  2
TGGGAA  2
TGGTAA  5
TGTCAA  5
TGTGAA  2
TTCCAA  13
TTGAAA  6
TTGCAA  4
TTTAAA  6
</code></pre>

<python><k-mer><dictionary><tsv>
Sort dictionary in descending order
# Sort dictionary in descending order

(Asked by: username_0 on 2023-01-31)

Hi I am looking to sort a list of kmers into descending order. I used KMC to obtain a list of kmers from a fastq file separated by tab (e.g.; kmer count). From there I have written this python script to attempt to sort the kmers and their counts in descending order:
import csv

with open("6mers.tsv") as kmer_file:
    
    tsv_reader = csv.DictReader(kmer_file, delimiter="\t")
    
    for kmer in tsv_reader:
        
        name = kmer["kmer"]
        
        count = kmer["count"]
        
        # section below attempts to sort the dictionary into descending order
        # taken from (https://www.freecodecamp.org/news/sort-dictionary-by-value-in-python/) 
        sorted_kmers = sorted(kmer.items(), key=lambda x:x[1], reverse=True)

        converted_dict = dict(sorted_kmers)
    
        print(converted_dict)

The code above outputs this:
{'kmer': 'TGCCAA', 'count': '2'}
{'kmer': 'TGGACA', 'count': '2'}
{'kmer': 'TGGGAA', 'count': '2'}
{'kmer': 'TGGTAA', 'count': '5'}
{'kmer': 'TGTCAA', 'count': '5'}
{'kmer': 'TGTGAA', 'count': '2'}
{'kmer': 'TTCCAA', 'count': '13'}
{'kmer': 'TTGAAA', 'count': '6'}
{'kmer': 'TTGCAA', 'count': '4'}
{'kmer': 'TTTAAA', 'count': '6'}

Clearly I am creating a separate dictionary for each kmer and it's count - I'm not sure how but I would like a result that looks more like this:
{'TTCCAA', '13'}
{'TTGAAA', '6'}
{'TTTAAA', '6'}
{'TGGTAA', '5'}
{'TGTCAA', '5'}
{'TTGCAA', '4'}
{'TGCCAA', '2'}
{'TGGACA', '2'}
{'TGGGAA', '2'}
{'TGTGAA', '2'}

Can someone help me fix my code so it works?
EDIT:
The .tsv file looks just like this:
TGCCAA  2
TGGACA  2
TGGGAA  2
TGGTAA  5
TGTCAA  5
TGTGAA  2
TTCCAA  13
TTGAAA  6
TTGCAA  4
TTTAAA  6

**Tags:** python, k-mer, dictionary, tsv

---

## 2 answers

### Answer by username_1 on 2023-02-01. Score: 2 | Accepted answer

Just make sure to cast the count to an integer prior to sorting. Assuming you need to do something with the counts, you could use:
import csv

from operator import itemgetter
from pprint import pprint


with open("6mers.tsv") as kmer_file:

    reader = csv.reader(kmer_file, delimiter="\t")
    counts = ((kmer, int(count)) for kmer, count in reader)

    sorted_kmers = sorted(counts, key=itemgetter(1), reverse=True)

    pprint(sorted_kmers)

Results:
[('TTCCAA', 13),
 ('TTGAAA', 6),
 ('TTTAAA', 6),
 ('TGGTAA', 5),
 ('TGTCAA', 5),
 ('TTGCAA', 4),
 ('TGCCAA', 2),
 ('TGGACA', 2),
 ('TGGGAA', 2),
 ('TGTGAA', 2)]

> **Comments:**
> **username_0**: This works! Thank you!  

---

### Answer by username_2 on 2023-01-31. Score: 1

This is untested code ... without seeing to the raw file its tricky.
Could you try:
import csv
with open("6mers.tsv") as kmer_file:
    tsv_reader = csv.DictReader(kmer_file, delimiter="\t")
    mydict = {rows[0]:rows[1] for rows in tsv_reader if not rows[0] == 'kmer'}

sorted_kmers = sorted(mydict.items(), key=lambda x:x[1], reverse=True)
print(sorted_kmers)

I'm assuming there is a header called 'kmer'

The output didn't work. The rows['kmers'] infers that (somehow) tsv_reader is already a dictionary (that's not how I thought it worked). Thus try,
import csv
with open("6mers.tsv") as kmer_file:
    tsv_reader = csv.DictReader(kmer_file, delimiter="\t")
    mydict = {rows['kmers']:rows['count'] for rows in tsv_reader}

sorted_kmers = sorted(mydict.items(), key=lambda x:x[1], reverse=True)
print(sorted_kmers)

Unless it's loaded as a singular dictionary with Kmer as the key and count as the value the sort line will not work. Once that format is achieved as a dictionary then it will work.
What I don't understand is where it's getting 'kmer' or 'count' from if there are no headers in the csv file. Something isn't right if the above code works.

> **Comments:**
> **username_0**: I tried the code you wrote but I got this error message: Traceback (most recent call last):    File ~/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py:356 in compat_exec     exec(code, globals, locals)    File ~/Desktop/new_try/untitled1.py:12     mydict = {rows[0]:rows[1] for rows in tsv_reader}    File ~/Desktop/new_try/untitled1.py:12 in <dictcomp>     mydict = {rows[0]:rows[1] for rows in tsv_reader}  KeyError: 0  
> **username_0**: There was a header that I manually added with "kmer" and "count" but the raw result file from KMC does not include that header so I want to try and do it without the header added in  
> **username_0**: I don't know why it's not working! It's so strange. I tried a different IDE just to make sure there wasn't a a bug with the one I was using but it really isn't working with either of them...  
> **username_0**: does "rows[0]" look for a specific instance of 0 in the keys?  
> **username_2**: @rimo what I think is happening is `csv` is automatically placing each column into a dictionary. Fine, I only use it to write out. What I don't understand is where the information for each column which is passed into the dictionary is being stored  - it could only be in the `tsv` file.  
> **username_2**: The reason I'm not up to date is I'd always open `csv` into `pandas`  
> **username_1**: @M__ You can just pass in a list of fieldnames, e.g. `csv.DictReader(kmer_file, fieldnames=['kmer', 'count'], delimiter="\t")`  
> **username_2**: @Steve Understand entirely, but the code in the questions doesn't carry any fieldnames, unless it is not the precise code that the OP is using.  
> **username_0**: This works except it orders them like this: 9, 8, 7, 66, 63, 6, 59, 55, 5, 4, 32, 3, 22, 2, 13, 12, 10, 1...is there a way to sort them by digits as well?  
> **username_2**: @rimo interesting it kind of works. The `sort` `lambda` isn't working however: the exact code you used I use all the time for sorting dictionaries using their value.  

---

