首页 > 解决方案 > Python Dictionary as tuple keys not increasing the values

问题描述

I've a list of list for example transactions = [['1','2','3','4','5','6'],['2','3','6','1','5','10],['6','4','5','6','4','3']] and a Dict with tuples as keys for example triplets = {(1,2,3): 0, (2,3,4):0} now i want to check if the keys of triplets are occurred in the transactions as (1,2,3) is in first nested list then I'll update the values of that key tuple ( It will become 1 from 0). if it is found in another list e.g. it is also available in the second list [2,3,6,1,5,10] then It's count will increase from 1 to 2. And this process will go on for the whole triplets.

I wrote this code but it's not increasing the count.

    for items in triplets.keys():
        if items in transactions:
            triplets[items] = triplets[items] + 1

if someone can edit the question title properly please. I can't find the right words to ask.

标签: pythonpython-3.xdictionarytuples

解决方案


解决方案

您可以使用set检查每个 ofkeys和 oftriplets的元素的sub-lists交集transactions。如果交集产生与 相同的结果key,则增加字典 key中的计数。triplets

transactions = [[1,2,3,4,5,6],[2,3,6,1,5,10],[6,4,5,6,4,3]]
transactions = [[str(e) for e in ee] for ee in transactions]
print('transactions: {}'.format(transactions))
triplets = {(1,2,3): 0, (2,3,4):0}
print('triplets: ')
print('\tBefore Update: {}'.format(triplets))

for key in triplets.keys():
    count = triplets.get(key)
    for t in transactions:
        s = set(list(key))
        count += int(set(t).intersection(s) == s)
    triplets.update({key: count})

print('\tAfter Update: {}'.format(triplets))

输出

transactions: [['1', '2', '3', '4', '5', '6'], ['2', '3', '6', '1', '5', '10'], ['6', '4', '5', '6', '4', '3']]
triplets: 
    Before Update: {(1, 2, 3): 0, (2, 3, 4): 0}
    After Update: {(1, 2, 3): 0, (2, 3, 4): 0}

推荐阅读