Results 1 to 3 of 3

Thread: about removing duplicate values from python dictionary ?

  1. #1
    Join Date
    Apr 2011
    Location
    Chittagong,Bangladesh
    Beans
    149
    Distro
    Ubuntu 14.04 Trusty Tahr

    about removing duplicate values from python dictionary ?

    Suppose
    Code:
    a={1: 'url.txt', 2: x, 3: x, 4: z, 5: 'fb.txt''}
    and i want this output
    Code:
    a={1:'url.txt',2:x,3:'fb.txt'}
    so i basically want to remove duplicate values ; but how ?

  2. #2
    Join Date
    May 2007
    Beans
    251

    Re: about removing duplicate values from python dictionary ?

    Quote Originally Posted by prismctg View Post
    Suppose
    Code:
    a={1: 'url.txt', 2: x, 3: x, 4: z, 5: 'fb.txt''}
    and i want this output
    Code:
    a={1:'url.txt',2:x,3:'fb.txt'}
    so i basically want to remove duplicate values ; but how ?
    You could invert the dict..
    something like:
    Code:
    inverted = dict()
    for (k, v) in a.iteritems():
        if not inverted.has_key(v):
            inverted[v] = k
    This is to also maintain the first key for a duplicated value -- otherwise, you can skip the "has_key()" check and it'll store only the last key of the duplicated value.

    To get back to original dict, you just need to invert this dict again - like:
    Code:
    new_dict = dict()
    for (k, v) in inverted.iteritems():
        new_dict[v] = k
    If you don't want to preserve the keys from original dict at all but just want integers as key, you could simply do:
    Code:
    new_dict = dict()
    i = 1
    for v in inverted.iterkeys():
        new_dict[i] = v
        i += 1
    HTH
    The Unforgiven

  3. #3
    Join Date
    Apr 2011
    Location
    Chittagong,Bangladesh
    Beans
    149
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: about removing duplicate values from python dictionary ?

    thank you so much

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •