Compare Python dictionary with list as value

Viewed 65

I am writing a parser bot for Steam that will keep track of which items come and go from a Steam user's inventory. I wrote a code that gets all the user's items and returns in the form of a dictionary with a nested list, where KEY = USER NAME, VALUE = ITEM NAME AND ITS QUANTITY. Now I need to compare Data1 and Data2 (updated data).

Data1 = {
            'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3)], 
            'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1)]

        }

Data2 = {
              
            'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3), ('M4A4', 1)], 
            'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1), ('GLOCK-18', 1)] 

        }

For example, a new item appears in Data2 and I need to write it to the third dictionary, keeping the key. The same must be done if items leave Data2 (it means that these items are no longer in the user's inventory).

Result = {
              
            'user1': [('M4A4', 1)], 
            'user2': [('GLOCK-18', 1)] 

        }
2 Answers

Use sets

result_addition = {d:list(set(Data2[d]) - set(Data1[d])) for d in Data2.keys()}
print(result_addition)

>> {'user1': [('M4A4', 1)], 'user2': [('GLOCK-18', 1)]}


result_missing = {d:list(set(Data1[d]) - set(Data2[d])) for d in Data2.keys()}
print(result_missing )

>> {'user1': [], 'user2': []}
def dict_diff(dict_1, dict_2):
    keys = set(dict_1.keys()).union(set(dict_2.keys()))
    result = {}
    for key in keys:
        if key not in Data1:
            result[key] = Data2[key]
            continue
        if key not in Data2:
            result[key] = Data1[key]
            continue
        
        diff1 = set(Data2[key]).difference(set(Data1[key]))
        diff2 = set(Data1[key]).difference(set(Data2[key]))
        
        
        result[key] = list(diff1.union(diff2))

    return result
                
    
dict_diff(Data1, Data2)
Related