[Tutor] Remove duplicate values from dictionary without removing key

Umar Draz unix.co at gmail.com
Fri Jan 8 08:50:59 EST 2021


Here is the Code

from pprint import pprint


items = [

    {'client': 'xyz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 100},

    {'client': 'xyz','name': "Abdelmadjid Tebboune", 'rating': 4.0,
'total': 100},

    {'client': 'xyz','name': "Alexander Lukashenko", 'rating': 3.1,
'total': 100},

    {'client': 'xyz', 'name': "Miguel Díaz-Canel", 'rating': 0.32, 'total':
100},

    {'client': 'udz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 150},

    {'client': 'udz', 'name': "Abdelmadjid Tebboune", 'rating': 4.0,
'total': 150},

    {'client': 'udz', 'name': "Alexander Lukashenko", 'rating': 3.1,
'total': 150},

    {'client': 'udz', 'name': "Miguel Díaz-Canel", 'rating': 0.32, 'total':
150}

]


seen = { "client":[], "name":[], "rating":[], "total": [] }


for dic in items:

  for field,value in dic.items():

    if value in seen[field]:

      dic[field] = ""

    else:

      seen[field].append(value)


pprint(seen)



and here is the output which is completely different then I had expected.



{'client': ['xyz', 'udz'],

 'name': ['Ilir Meta',

          'Abdelmadjid Tebboune',

          'Alexander Lukashenko',

          'Miguel Díaz-Canel'],

 'rating': [0.06, 4.0, 3.1, 0.32],

 'total': [100, 150]}

On Fri, Jan 8, 2021 at 6:25 PM Alan Gauld <alan.gauld at yahoo.co.uk> wrote:

> Please always use Reply All or reply List when reponding to list emails,
> otherwise
> they only go to the individual person who posted. I've CCd the list on
> this reply.
>
>
> On 08/01/2021 12:24, Umar Draz wrote:
> > I am totally new in Python, so if there is any example then it will be
> > helpful for me,
> >
> OK, Lets take it one bit at a time.
>
> In your case you want in pseudo code:
>
>
> seen = { "client":[], "name:[], "rating":[], "total": [] }
>
> >
> >     for each dictionary in the list
> >
> for dic in items:
>
> >         for each field in the dictionary
> >
>      for field,value in dic.items():
>
> >            check if the value has already been seen
> >
>             if value in seen[field]:
>
> >            if so replace the value with ""
> >
>                  dic[field] = ""
>
> >            else store the value for future reference but do not change
> it.
> >
>             else: seen[field].append(value)
>
>
> And that should work, although I haven't tested it so there may be some
> minor errors,
> which I'll leave as an exercise! :-).
>
> Try it and if you can't get it to work come back with a cut n paste of
> your exact
> code plus any error messages you get (in full)
>
> --
>
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>

-- 
Umar Draz


More information about the Tutor mailing list