过滤列表中的值 [英] filter list of values in a dictionary
问题描述
我有一个名为的字典hash_vs_file
键是 file_hash
值为 file_path
(一个或多个文件路径的列表)
I have a dictionary called hash_vs_file
keys are file_hash
values are file_path
(a list of one or more filepaths)
我想隔离并打印列表更长的项目超过一个文件路径。
I want to isolate and print only the items where the list is longer than one filepath.
我正在尝试,没有结果:
I'm trying, without result:
for file_hash in hash_vs_file:
if len(file_path) > 1 in hash_vs_file.items():
print file_hash
print file_path
推荐答案
使用 iteritems()
这样做:
Use iteritems()
this way instead:
for file_hash, file_path in hash_vs_file.iteritems():
if len(file_path) > 1:
print file_path
print file_hash
因为你做的那样,你只收到字典的键,所以检查 file_path
的长度失败。
Because the way you did, you are getting only the keys of the dictionary so checking the length of file_path
fails.
更新: / strong>
Update:
您要求输出的可读性。
您可以通过以下方式激励自己:
You asked for the readability of the output. You can inspire yourself from this method:
print file_path, file_hash
或者这个更好的依赖于 format()
:
Or this better one which relies on format()
:
print "File Path: {} ------ File Hash: {}".format(file_path,file_hash)
或者,如果您希望它看起来像一个列表,请尝试改为:
Or, if you want it to look like a list, try this instead:
print "[{}, {}]".format(file_path,file_hash)
这篇关于过滤列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!