Display values and how many times they occured using a Dictionary

Posted by user1730056 on Stack Overflow See other posts from Stack Overflow or by user1730056
Published on 2012-10-15T07:20:29Z Indexed on 2012/10/15 9:37 UTC
Read the original article Hit count: 161

Filed under:

I've been told to

By using a dictionary (or your solution to Part 4), write a method at_least(a, n) that takes a list, a, and an integer, n, as arguments and returns a list containing only the elements of a that occur at least n times. For complete marks, the list should contain the elements in order of their first occurrence in a.

I was able to figure this without using a dictionary, with

def at_least2(a, n):
    return [x for x in a if a.count(x) is n]

I was wondering how I can write this using a dictionary?

The input is:

a = [-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, 
     -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]

def at_least(a, 2):

and the output:

[8, 7, 2, -9, 1, -3, 2, -8, 7, 8, 2, -7, 1, -9, -3, -7, -3, 6, -3, 6, -3, -8]

Edit:

I don't understand how a dictionary is being used, yet the output isn't in dictionary form? My understanding is that dictionaries have values for each object. I'm not sure if I'm using the right terms.

© Stack Overflow or respective owner

Related posts about python