我想找到在 python 中迭代 key 中的值的最佳方法。
我有具有该结构的文件:
17 key1
18 key1
45 key2
78 key2
87 key2
900 key3
92 key4
所以我需要将第二列设置为键(不重复)并将与其对应的所有值(第一列)链接到该键。
'key1':['17','18']
'key2':['45','78','87']
'key3':['900']
'key4':['92']
到目前为止,我没有使用字典:
for line in file:
value, key = line.strip().split(None,1)
然后我可以用
将其放入字典中 diction.setdefault(key, []).append(value)
所以之后我就有了一本我需要的很好的字典。
但之后我必须重新读取文件以进行更改。更改可以发生在键(对)(添加/删除)中,也可以仅发生在值(添加/删除)中。如何检查迭代键值是否发生更改?
更新***: 对于 key 检查或多或少是清楚的:
if diction[key]:
但是如何迭代键内的值呢? 我需要找到差异,然后从字典中添加\删除这个值\对(如果是键的最后一个值)?
我想这可以通过一些 iteritem()\itervalues() 或 smthng 来完成,但我对此并不熟悉。
感谢您的帮助。
更新***
谢谢@Joël。最后我用了3张支票。首先是添加的任何键:
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
然后,如果我没有捕获或已经处理了这种情况,我将使用您的函数:
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]
最佳答案
我的建议是,如果你必须重新读取输入文件,你不妨重新创建你的字典,但这取决于字典创建所需的时间。根据您的要求,也许分析文件中的差异并更新字典会更快。
你可以看看difflib
模块,然后分析差异。在此基础上,可以在字典中删除删除内容,根据需要添加添加内容。
可悲的是,我打赌你会很难理解它的输出:这是人类可读的,而不是机器可读的,所以可能有更好的答案。
<小时/>编辑如果您想跟踪两个文件版本之间的更改(如评论中所写),您可以比较字典。对于 key ,您已经拥有所需的东西。
现在,对于更新的值:如果您确定您的值始终是字符串列表,那么您可以执行与比较 dict 键相同的操作:
>>> def comp(old_dict, new_dict):
... for key, old_val in old_dict.items():
... new_val = new_dict[key] # warning: to be used on keys in both dict
... 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]
# now testing on a simple example
>>> o = {'key1': ['a', 'b', 'c']}
>>> n = {'key1': ['b', 'c', 'd']}
>>> comp(o, n)
evolutions for key1
new content: ['d']
removed content: ['a']
警告:只有当 new_dict
包含 old_dict
的所有键时,此函数才有效,否则创建 new_val
将失败。您可以通过在函数中添加键的比较来轻松解决这个问题:
old_dict
中不在new_dict
中的键将被删除;new_dict
中而非old_dict
中的键是添加键。
请在您的答案中发布您的结果,以便其他人可以从中受益。
关于python - python中通过键迭代字典多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7996349/