Home > Mobile >  Updating Duplicate Dictionaries in Python
Updating Duplicate Dictionaries in Python

Time:11-25

I am trying to remove the duplicate values in python dictionary.

We have a snippet like below,

I want to make use of "Number" Key and remove the duplicates by updating them.

[
{
'Message': 'Fetched',
'Code': '200',
'Number': '20290775'
}, 
{
'Message': 'Fetched',
'Code': '202',
'Number': '20290776'
}, 
{
'Message': '',
'Code': '',
'Number': '20290775'
}, 
{
'Message': '',
'Code': '',
'Number': '20290776'
}, 
{
'Message': '',
'Code': '',
'Number': '20290777'
}, 
{
'Message': '',
'Code': '',
'Number': '20290778'
}, 
{
'Message': '',
'Code': '',
'Number': '20556729'
}

]

How can we generate into below snippet

[ 
{
'Message': 'Fetched',
'Code': '200',
'Number': '20290775'
}, 
{
'Message': 'Fetched',
'Code': '200',
'Number': '20290776'
}, 
{
'Message': '',
'Code': '',
'Number': '20290777'
}, 
{
'Message': '',
'Code': '',
'Number': '20290778'
}, 
{
'Message': '',
'Code': '',
'Number': '20556729'
}

]

Is it Possible to generate and remove the duplicate dictionary values?

CodePudding user response:

You can do something like this to remove duplicates based on number:

result = []
for item in input_list:
    for element in result:
        if item["Number"] == element["Number"]:
            break
    else:
        result.append(item)
print(result)

For your example, this will output:

[{'Message': 'Fetched', 'Code': '200', 'Number': '20290775'}, {'Message': 'Fetched', 'Code': '202', 'Number': '20290776'}, {'Message': '', 'Code': '', 'Number': '20290777'}, {'Message': '', 'Code': '', 'Number': '20290778'}, {'Message': '', 'Code': '', 'Number': '20556729'}]

CodePudding user response:

mylist = [ value for value in { value['number']:value for value in mylist }.values() ]

  • Related