data is below
JavaScript
x
8
1
data = [["'id'", "'state'", "'country'n"],
2
['44', "'WD'", "'India'n"],
3
['5', "'WD'", "'India'n"],
4
['44', "'WD'", "'Japan'n"],
5
['390', "'WD'", "'Japan'n"],
6
['17', "'WD'", "'Japan'n"],
7
['17', "'WD'", "'BEL'"]]
8
How to remove the duplicate elements in id.
Here 44, 17 id is repeating
Expected
JavaScript
1
6
1
[["'id'", "'state'", "'country'n"]
2
['44', '1', "'WD'", "'India'n"]
3
['5', "'WD'", "'India'n"]
4
['390', "'WD'", "'Japan'n"]
5
['17', "'WD'", "'Japan'n"]]
6
Pseudo code
JavaScript
1
9
1
l = []
2
3
for i in range(len(a)):
4
print (a[i])
5
if i[0] == a[i][1]:
6
pass
7
else:
8
l.append(i)
9
Advertisement
Answer
You can use a dict
here:
JavaScript
1
8
1
unique_data = {}
2
3
for sub_data in data:
4
sub_data_id = sub_data[0]
5
6
if sub_data_id not in unique_data:
7
unique_data[sub_data_id] = sub_data
8
The structure of unique_data
will be like this:
JavaScript
1
8
1
{
2
"'id'": ["'id'", "'state'", "'country'"],
3
'44': ['44', '1', "'WD'", "'India'"],
4
'5': ['5', "'WD'", "'India'"],
5
'390': ['390', "'WD'", "'Japan'"],
6
'17': ['17', "'WD'", "'Japan'"]
7
}
8
To then get the unique items, we can use list(unique_data.values())
, which gives us:
JavaScript
1
2
1
[["'id'", "'state'", "'country'"], ['44', '1', "'WD'", "'India'"], ['5', "'WD'", "'India'"], ['390', "'WD'", "'Japan'"], ['17', "'WD'", "'Japan'"]]
2