Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary error: cannot convert dictionary update sequence element #0 to a sequence

I’m trying to count the frequency from a list. I received an type error

mylist = [1, 1, 1, 2, 3, 3, 4]
def frequency(x):
    counts = dict()
    if x in counts:
        counts[x] += 1
    elif len(counts) < 3:
        counts.update([x, 1])            
    return counts
for x in mylist:
    frequency(x)

I received TypeError: cannot convert dictionary update sequence element #0 to a sequence on counts.update([x, 1]). I checked what this error is about, but I cannot see I violated it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Fix

The counts should be created outside, so before, if you create it in the method, that will be new one each time

You may update a dict with another dict, not a list

counts.update({x: 1})

Improve logic

  • simply do counts[x] = 1 instead, that’s cheaper
  • it woul be better that the method does the whole frequency computation, from a list
counts = {}
def frequency(values):
    for x in values:
        if x in counts:
            counts[x] += 1
        else:
            counts[x] = 1
    return counts

mylist = [1, 1, 1, 2, 3, 3, 4]
counts = frequency(mylist)
print(counts)  # {1: 3, 2: 1, 3: 2, 4: 1}

Improve code

There is method that could help you get nicer code

  • collections.defaultdict that handles if the key isn’t present (set 0, as we told him int)

    def frequency(values):
        counts = defaultdict(int)
        for x in values:
            counts[x] += 1
        return counts
    
  • the master of all collections.Counter

    def frequency(values):
        return Counter(values)
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading