I want to merge two lists and get data matched without duplicates and to alias them to new structure
I have two lists
here is a given two list try to merge
cats = [
'orange', 'apple', 'banana'
]
and second list
types = [
{
"id": 1,
"type": "orange"
},
{
"id": 2,
"type": "apple"
},
{
"id": 3,
"type": "apple"
},
{
"id": 4,
"type": "orange"
},
{
"id": 5,
"type": "banana"
}
]
and I want to combine them to get this result:
[
{'orange': {
'UNIT': [1, 4]
}
},
{'apple': {
'UNIT': [2, 3]
}
},
{'banana': {
'UNIT': [5]
}
}
]
and my code, this after my tries i get this result :
for item in types:
for cat in cats:
if item['type'] == cat:
matched.append(
{
cat: {
"UNIT": [i['id'] for i in types if
'id' in i]
}
}
)
and my result is like this
[{'orange': {'UNIT': [1, 2, 3, 4, 5]}},
{'apple': {'UNIT': [1, 2, 3, 4, 5]}},
{'apple': {'UNIT': [1, 2, 3, 4, 5]}},
{'orange': {'UNIT': [1, 2, 3, 4, 5]}},
{'banana': {'UNIT': [1, 2, 3, 4, 5]}}]
3
Answers
With list comprehension:
Your problem is the
in
inside your list comprehension – beside that your code is complex. You get multiples due to your for loops and never checking if that fruit was already added tomatched
.To reduce the 2 lists to the needed values you can use
which leads to an easier dictionary with all the data you need:
From there you can build up your overly complex list of dicts with 1 key each:
to get
Answer to extended problem from comment:
If you need to add more things you need to capture you can leverage the fact that lists and dicts store by ref:
to get
Here is an alternative approach using
filter()
method and lambda.