Filter List Of Values In A Dictionary
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 longe
Solution 1:
Use iteritems()
this way instead:
for file_hash, file_path in hash_vs_file.iteritems():
iflen(file_path) > 1:
print file_path
print file_hash
Because the way you did, you are getting only the keys of the dictionary so checking the length of file_path
fails.
Update:
You asked for the readability of the output. You can inspire yourself from this method:
print file_path, file_hash
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)
Solution 2:
for file_hash, file_path in hash_vs_file.items():
iflen(file_path) > 1:
print file_hash
print file_path
The method .items()
gives you a tuple of key and value.
You can unpack this tuple with file_hash, file_path
, so that
you have access to each file_hash
and file_path
in each iteration.
Solution 3:
Alternatively, you can use the filter built in function to return an iterator like so:
for file_hash infilter(lambda key: len(hash_vs_file[key]) > 1, hash_vs_file):
print("{} : {}".format(file_hash, hash_vs_file[file_hash]))
Or you can use dict comprehension for a newly filtered dictionary:
hash_vs_file = {fhash: fpath for fhash, fpath in hash_vs_file.items() iflen(fpath) > 1}
print(hash_vs_file)
Post a Comment for "Filter List Of Values In A Dictionary"