Re: Find duplicates in a list and count them ...

Discussion in 'Python' started by MRAB, Mar 26, 2009.

  1. MRAB

    MRAB Guest

    Benjamin Kaplan wrote:
    >
    >
    > On Thu, Mar 26, 2009 at 5:14 PM, <
    > <mailto:p>> wrote:
    >
    > Hi D'Arcy J.M. Cain,
    >
    > Thank you. I tried this and my list of 76,979 integers got reduced
    > to a dictionary of 76,963 items, each item listing the integer value
    > from the list, a comma, and a 1. I think what this is doing is
    > finding all integers from my list that are unique (only one instance
    > of it in the list), instead of creating a dictionary with integers
    > that are not unique, with a count of how many times they occur. My
    > dictionary should contain only 11 items listing 11 integer values
    > and the number of times they appear in my original list.
    >
    >
    >
    > Not all of the values are 1. The 11 duplicates will be higher. Just
    > iterate through the dict to find all keys with values > 1.
    >
    > >>> icounts

    > {1: 2, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 5, 8: 3, 9: 1, 10: 1, 11: 1}
    >
    > Python 2.x :
    > >>> dups = {}
    > >>> for key, value in icounts.iteritems() :

    > ... if value > 1 :
    > ... dups[key] = value
    > ...
    > >>> dups

    > {8: 3, 1: 2, 7: 5}
    >
    >
    > Python 3.0 :
    > >>> dups = {key:value for key, value in icounts.items() if value > 1}
    > >>> dups

    > {8: 3, 1: 2, 7: 5}
    >

    The equivalent in Python 2.x would be:

    >>> dups = dict((key, value) for key, value in icounts.iteritems() if

    value > 1)
    >>> dups

    {8: 3, 1: 2, 7: 5}
     
    MRAB, Mar 26, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anonieko

    HttpHandlers - Learn Them. Use Them.

    Anonieko, Jun 15, 2006, in forum: ASP .Net
    Replies:
    5
    Views:
    538
    tdavisjr
    Jun 16, 2006
  2. D'Arcy J.M. Cain
    Replies:
    1
    Views:
    587
    Paul Rubin
    Mar 26, 2009
  3. Replies:
    1
    Views:
    482
    John Machin
    Mar 26, 2009
  4. why the lucky stiff
    Replies:
    5
    Views:
    155
    why the lucky stiff
    Sep 22, 2004
  5. basi
    Replies:
    4
    Views:
    176
    Wayne Vucenic
    Aug 1, 2005
Loading...

Share This Page