I want to find most optimal way to iterate values in key in python.
I have file with that structure:
17 key1
18 key1
45 key2
78 key2
87 key2
900 key3
92 key4
so I need to set the second column as key(with no repetition) and link to this key all the values (first column) corresponding to it.
'key1':['17','18']
'key2':['45','78','87']
'key3':['900']
'key4':['92']
Up to now I do it without using the dictionary:
for line in file:
value, key = line.strip().split(None,1)
And then I can put it into the dictionary with
diction.setdefault(key, []).append(value)
so after that I have a nice dictionary as I needed.
But after that I have to reread file for changes. changes can occur in keys(pairs) (adding/removing) or only in value (adding/removing) How can I check if change occured by iteration keys by values?
UPD***: for keys check is more or less clear:
if diction[key]:
but how to iterate values inside the key? I need to find the difference, and then add\remove this value\pair(if last value of the key) from dictionary?
I suppose it can be done with some iteritem()\itervalues() or smthng but I m not familiar with that.
Thank you for help.
UPD***
Thank you @Joël. Finally I used 3 checks. first is any keys added:
set_old_dict = set(new_old.keys())
set_new_dict = set(new_dict.keys())
intersect = set_new_dict.intersection(set_old_dict)
def added(self):
return set_new_dict - intersect
def removed(self):
return set_old_dict - intersect
And then if I do not catch or have already processed this situations I will use your function:
def comp(old_dict, new_dict):
for key, old_val in old_dict.items():
new_val = new_dict[key]
print 'evolutions for', key
print 'new content:', [x for x in new_val if x not in old_val]
print 'removed content:', [x for x in old_val if x not in new_val]