Remove duplicate values from dictionary without removing key

Louis Krupp lkrupp at invalid.pssw.com.invalid
Sat Jan 9 00:33:51 EST 2021


On 1/8/2021 2:56 AM, Umar Draz wrote:
> I want to replace duplicate values with empty "" in my dictionary. Here is
> my original dictionary.
>
> 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': 100},
>      {'client': 'udz', 'name': "Alexander Lukashenko", 'rating': 3.1,
> 'total': 150},
>      {'client': 'udz', 'name': "Miguel Díaz-Canel", 'rating': 0.32, 'total': 150}
> ]
>
>
> 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': '', 'name': "Miguel Díaz-Canel", 'rating': 0.32, 'total': ''},
>      {'client': 'udz', 'name': "Ilir Meta", 'rating': 0.06, 'total': 150},
>      {'client': '', 'name': "Abdelmadjid Tebboune", 'rating': 4.0, 'total': ''},
>      {'client': '', 'name': "Alexander Lukashenko", 'rating': 3.1, 'total': ''},
>      {'client': '', 'name': "Miguel Díaz-Canel", 'rating': 0.32, 'total': ''}
> ]
>
>
> Would you please help me how I can do this? and if this is not the right
> place to ask this question then please help me where I can ask this? I had
> tried stackoverflow but that not worked.

items isn't a dictionary; as MRAB mentioned, it's a list of 
dictionaries. Each dictionary in items looks like a database record with 
fields (client, name, rating, and total).

When you say you want to replace duplicate client fields by "", it 
almost looks like you're getting ready to print a report that looks 
something like this:

xyz    Ilir Meta                              0.06    100
           Abdelmadjid Tebboune    4.00    100
           Alexander Lukashenko     3.10
...

where the report will look better when duplicate client values aren't 
printed.

If that's the case, there are almost certainly better ways to do it. 
Changing values in items might have unforeseen consequences, since once 
duplicate client fields have been wiped out, there's no way to retrieve 
items[1]["client"] without looking at items[0]. And if the list of items 
is ever reordered, some of the client fields will be lost for good.

I hope this helps.

Louis


More information about the Python-list mailing list