2017-03-21 81 views
1

我在python中創建了一個字典,這是它的一些示例代碼。在Python 2中搜索字典

filesAndHashes = dict() 
... 
>>>print filesAndHashes 
{ 
"/home/rob/Desktop/test.txt":"1c52fe8fbb1463d541c2d971d9890c24", 
"/home/rob/Desktop/file.dat":"6386ba70e82f11aa027bfc9874cd58cb", 
"/home/rob/Desktop/test2.exe":"5b73c2a88fab97f558a07d40cc1e9d8e" 
} 

所以這一切都是文件路徑和文件的MD5。

所以我現在想要做的是,我找到了一些感興趣的MD5,並創建了它們的列表,並且希望在我的列表中爲每個MD5搜索字典並將每個哈希的文件路徑返回給我。

此外,程序的工作方式,我的列表中不會有一個不在字典中的MD5,所以不用擔心錯誤檢查。

請隨時索要我的信息

謝謝。

+0

散列保證是唯一的嗎? – timgeb

+0

是@timgeb,因爲它只會掃描最多約6個文件 –

回答

2

你有一個路徑 - >哈希映射,但你需要一個哈希 - >路徑映射。假設哈希值是唯一的,扭轉字典

>>> filesAndHashes = {'foo': '123', 'bar': '456'} 
>>> hashesAndFiles = {hash:fname for fname,hash in filesAndHashes.iteritems()} 
>>> hashesAndFiles 
{'123': 'foo', '456': 'bar'} 

現在只是遍歷你的清單,報告相符:

>>> hashes = ['456'] 
>>> for hash in hashes: 
...  filename = hashesAndFiles[hash] 
...  print(filename) 
... 
bar 

如果您不能排除哈希不是唯一的,這在理論上是可能的,使用defaultdict。根據需要

>>> from collections import defaultdict 
>>> hashesAndFiles = defaultdict(list) 
>>> 
>>> filesAndHashes = {'foo': '123', 'bar': '456', 'baz': '456'} 
>>> for fname, hash in filesAndHashes.items(): 
...  hashesAndFiles[hash].append(fname) 
... 
>>> hashesAndFiles 
defaultdict(<type 'list'>, {'123': ['foo'], '456': ['baz', 'bar']}) 
>>> 
>>> hashes = ['456'] 
>>> for hash in hashes: 
...  for filename in hashesAndFiles[hash]: 
...   print(filename) 
... 
baz 
bar 

捕捉KeyErrors(從你的問題我以爲你不希望在你的列表中的任何不存在的哈希值)。

0

反轉字典,以便鍵是哈希,因爲您想使用哈希搜索。

然後只需搜索在字典中鍵:filesAndHashes_reversed.get(hash_value, None)

filesAndHashes_reversed = { value: key for key, value in filesAndHashes.iteritems() } 
hash_list = [ hash_1,hash_2, hash_3, ] 
for hash in hash_list: 
    if filesAndHashes_reversed.get(hash, None) == None: 
     print("Not Found") 
    else: 
     print(filesAndHashes_reversed.get(hash, None)) 
0

也許你沒有使用正確的方法,但首先我會回答問題。

要查找的第一場比賽,你可以這樣做:

def find_item(md5hash) 
    for k,v in a.iteritems(): 
    if v == md5hash: 
     return k 

注意,這是第一場比賽。理論上,可能有多個條目具有相同的散列,但OP已經表示散列預期是唯一的。但在那種情況下,爲什麼不把它們用作關鍵?這可以很容易地搜索它們:

hashes_and_files = dict() 

hashes_and_files["1c52fe8fbb1463d541c2d971d9890c24"]="/home/rob/Desktop/test.txt" 
hashes_and_files["6386ba70e82f11aa027bfc9874cd58cb"]="/home/rob/Desktop/file.dat" 
hashes_and_files["5b73c2a88fab97f558a07d40cc1e9d8e"]="/home/rob/Desktop/test2.exe" 

#finding is trivial 

find_hash = "5b73c2a88fab97f558a07d40cc1e9d8e" 
file_name = hashes_and_files["5b73c2a88fab97f558a07d40cc1e9d8e"]