0
down vote
favorite
I’m trying to match lists with dictionaries in list of lists.
I have had help before in the forum but I have another doubt of how to make it perfect match.
I want to compare x number of lists in list of lists and that lists contain dictionaries. So I want to compare the dictionaries in these lists based on the name key in the dictionaries. If it matches it should pass, if not it should copy the whole dictionary to the lists that don’t have it with editing the balance key value to 0.
here is my list example :
l = [
[
{'name': u'Profit', 'balance': 10,'in_type':'Something'},
{'name': u'Income', 'balance': 30,'in_type':'Something'},
],
[
{'name': u'Profit', 'balance': 20,'in_type':'Something'},
{'name': u'Income', 'balance': 10,'in_type':'Something'},
{'name': u'NotIncome', 'balance': 15,'in_type':'AnotherThing'}
],
[]
]
So the result should be :
l = [
[
{'name': u'Profit', 'balance': 10,'in_type':'Something'},
{'name': u'Income', 'balance': 30,'in_type':'Something'},
{'name': u'NotIncome', 'balance': 0,'in_type':'AnotherThing'}
],
[
{'name': u'Profit', 'balance': 20,'in_type':'Something'},
{'name': u'Income', 'balance': 10,'in_type':'Something'},
{'name': u'NotIncome', 'balance': 15,'in_type':'AnotherThing'}
],
[{'name': u'Profit', 'balance': 0,'in_type':'Something'},
{'name': u'Income', 'balance': 0,'in_type':'Something'},
{'name': u'NotIncome', 'balance': 0,'in_type':'AnotherThing'}]
]
And here is the code :
import pprint
l = [
[
{ 'name': u'Profit' , 'balance': 10,'in_type':'Something'},
{'name': u'Income','balance': 30,'in_type':'Something'},
{'name': u'NotIncome','balance': 15,'in_type':'AnotherThing'},
],
[
{'name': u'Profit','balance': 20,'in_type':'Something'},
{'name': u'Income','balance': 10,'in_type':'Something'},
],
[]
]
all_type = {d['in_type'] for x in l for d in x}
all_names = {d['name'] for x in l for d in x}
for sub_list in l:
for name,type in zip((all_names - {d['name'] for d in sub_list}),(all_type - {d['name'] for d in sub_list})):
sub_list.append({'name': name, 'balance': 0,'type':??????})
pprint.pprint(l)