Search code examples
pythoncollectionsdefaultdict

How to print this collections.defaultdict in descending order in python?


I am counting the frequencies of addresses from a csv file, and then printing the address and the counts. The csv file contains many fields so I choose only the fields I need.

Unfortunately, the printing happens unordered. How can I print it in descending order?

Below is the simplified code. I'm also using a set (owners) but I've removed the code related to it to keep the question simple.

import csv
import collections 

multiOwner = collections.defaultdict(lambda: {'freq': 0, 'owners': set()})

with open('input.csv', newline="") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    for folio,owner1,owner2,address, *rest in csv_reader:
        multiOwner[address]['freq'] += 1
        
    for address in multiOwner:
        print (address,multiOwner[address]['freq'])

Solution

  • You may want to use the SortedDict from the SortedContainers library. It's easy to use, written in pure Python, and surprisingly efficient. However I don't think they offer a SortedDefaultDict.

    Otherwise you can extract a sorted list of the keys and iterate over that list:

    keys=sorted(list(multiOwner.keys()), key=lambda x:multiOwner[x]['freq'], reverse=True)
    for k in keys:
        print(k, multiOwner[k]['freq'])