[Tutor] Remove duplicate values from dictionary without removing key

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jan 8 07:14:21 EST 2021


On 08/01/2021 09:44, Umar Draz wrote:
> I want to replace duplicate values with empty "" in my dictionary. Here is
> my original dictionary.

It is extremely important in programming to use terms accurately.
You do not in fact have a dictionary, you have a list of dictionaries.
You do not want to replace duplicate values you want to replace single
field values where previous dictionaries have had the same value in
the same field. (If the criteria is more complex than that then
please spell it out in detail, that will make the code you need
to write more obvious)

Using the correct terms means you can create an accurate description
of your problem. Very often when you do that the solution will
become clearer.

In your case you want in pseudo code:

for each dictionary in the list
    for each field in the dictionary
       check if the value has already been seen
       if so replace the value with ""
       else store the value for future reference but do not change it.

Can you convert that pseudo code to Python?
Hint: For the previously seen values you could store them
      in lists in another, separate dictionary called seen:

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

It should be relatively simple. If you have difficulty get back to us.

> 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': 'udz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 150},
>     {'client': 'udz', 'name': "Abdelmadjid Tebboune", 'rating': 4.0,
> 'total': 100},

> Now I want to create another dict with like this
> 
> items = [
>     {'client': 'xyz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 100},
>     {'client': '','name': "Abdelmadjid Tebboune", 'rating': 4.0, 'total': ''},
>     {'client': '','name': "Alexander Lukashenko", 'rating': 3.1, 'total': ''},
>     {'client': 'udz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 150},
>     {'client': '', 'name': "Abdelmadjid Tebboune", 'rating': 4.0, 'total': ''},


-- 
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




More information about the Tutor mailing list