[Tutor] Remove duplicate values from dictionary without removing key
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Jan 8 10:25:00 EST 2021
On 08/01/2021 14:18, Umar Draz wrote:
> Hi Alan
>
> I have changed the function and now it is working as I want
>
> *def**remove_duplicate_values*(dict_list):
>
> seen = {}
>
> *for*key *in*dict_list[0].keys():
>
> seen[key] = []
>
>
> *for*dic *in*dict_list:
>
> *for*field,value *in*dic.items():
>
> *if*field == *'client'*:
>
> *if*value *in*seen[field]:
>
> dic[field] = ""
>
> *else*: seen[field].append(value)
>
> *return*dict_list
>
>
OK, For a single field I would suggest simplifying it slightly.
*def**remove_duplicate_values*(dict_list, field):
seen = []
*for*dic *in*dict_list:
*if*dic[field]*in*seen:
dic[field] = ""
*else*: seen.append(value)
*return*dict_list
That way you can still use it for other fields if
necessary and for 'client' simply call it as
items = remove_duplicate_values(items,"client")
To remove dups in multiple fields just call it
repeated times with different field names. (Notice
that your original mail's example removed more
than the client field duplicates!)
--
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