Reputation: 18727
I have a list of "Bank application type" "bank name" and their local ID values. like:
BANKS = [
(1, "Bank A Web", "BankA"),
(2, "Bank B ATM", "BankB"),
(3, "Bank A Wap", "BankA"),
(4, "Bank C", "BankC"),
]
I want to categorize their IDs according to their bank name so I used a simplified list for this purpose
BANKS_CATS = [
(1, "BankA"),
(2, "BankB"),
(3, "BankA"),
(4, "BankC"),
]
I want to match each bank Id with other associated bank IDs (different services from the same bank)
{1: [1, 3],
2: [2],
3: [1, 3],
4: [4]}
Also that value list is a simplified example, my actual bank names and bank service names are different and do not have a similar pattern to match to categorize them.
I ordered my actual list
my_new_list = sorted(BANKS_CATS, key=lambda s: s[1])
then try to group it
from itertools import groupby
grouped = groupby(my_new_list, key=lambda s: s[1])
but form that point on, I could not achieve what I want.. I try to iterate over the grouped values with no success.
How can I achieve required result from this point?
Upvotes: 1
Views: 105
Reputation: 239443
my_list = [
(1, "BankA"),
(2, "BankB"),
(3, "BankA"),
(4, "BankC"),
]
ids, result = {}, {}
for num, bank in my_list: ids.setdefault(bank, []).append (num)
for num, bank in my_list: result[num] = ids[bank]
print result
Output
{1: [1, 3], 2: [2], 3: [1, 3], 4: [4]}
Upvotes: 2
Reputation: 209
This is a one line code without dependencies:
{int(t[1][4:]):[i[0] for i in my_list if i[1] == t[1]] for t in my_list}
first gathers groups from my_list, and then finds values in my_list for each group.
Upvotes: 0