2016-11-07 93 views
0

我有兩個字典文件,我想比較。我需要知道一個字典中的值是否出現在另一個字典中。鑰匙是不一樣的,所以我不能去基於鑰匙。Python閱讀兩個字典比較值,並創建第三個字典

目標:

  1. 是否相同的值在兩個字典存在嗎?
  2. 打印不在其他字典中出現的值。
  3. 使用鍵,字典中匹配的值以及將字典打印到屏幕的值創建新詞典。

我可以搜索這兩個字典並找到69個不同的條目。

我的問題是:

  1. 我懷疑有這樣做的,
  2. 的更簡單的方法,我總懷疑有更好的方法。
  3. 我沒有創建第三個字典與匹配的兩個值/鍵。

目前代碼:

#!/usr/bin/python 

# Open Files and Build dictionaries. 

ackg2shipping = open('AirCheckG2_ShippingLog.txt', 'r', encoding='ascii') 
dAckg2 = {} 
for line in ackg2shipping: 
    if not line.strip(): 
     continue 
    row = line.split(',') 
    # creating unique key as one does not exist in file: 
    mfgDate = row[2] 
    serialNumber = row[5] 
    dAckg2[mfgDate] = serialNumber 

macAddressLog = open('MacAddress.dat', 'r', encoding='ascii') 
dMacaddress = {} 
for line in macAddressLog: 
    if not line.strip(): 
     continue 
    row = line.replace(", ", ",").split(',') 
    macAddress = row[0] 
    serialNum2 = row[1] 
    if serialNum2.find("_2") != -1: 
     continue 
    if serialNum2.find("HM") != -1: 
     continue 
    if serialNum2.find("-") != -1: 
     continue 
    if serialNum2.find("Min") != -1: 
     continue 
    if serialNum2.find("Max") != -1: 
     continue 
    dMacaddress[macAddress] = serialNum2 

for ackValue, macValue in zip(dAckg2.items(), dMacaddress.items()): 
     if ackValue == macValue: 
      print('Ok', ackValue, macValue) 
     else: 
      print('Not', ackValue, macValue) 


match = 0 
nomatch = 0 

for ackKey, ackValue in dAckg2.items(): 
    for macKey, macValue in dMacaddress.items(): 
     if ackValue == macValue: 
      # print("Debug: ", macValue, ackValue, "Match") 
      match += 1 
     else: 
      # print("no match") 
      # print("Debug: ", macValue, ackValue) 
      nomatch += 1 

print("Matched: ", match) 
print("Not Matched:", nomatch) 

match = 0 
nomatch = 0 
for macKey, macValue in dMacaddress.items(): 
    for ackKey, ackValue in dAckg2.items(): 
     if macValue == ackValue: 
      # print("Debug: ", macValue, ackValue, "Match") 
      match += 1 
     else: 
      # print("no match") 
      # print("Debug: ", macValue, ackValue) 
      nomatch += 1 

print("Matched: ", match) 
print("Not Matched:", nomatch) 
missingSerials = (len(dAckg2) - match) 
# noinspection PyPep8 
print(missingSerials) 

回答

1

如果你只關心的值,該dict.values()方法可能是你想要的東西。

d1_values = set(d1.values()) 
d2_values = set(d2.values()) 
in_both = d1_values & d2_values 
not_in_both = d1_values^d2_values 

我不確定你的第三個要求究竟是什麼。是這樣的嗎?

new_dict = {} 
for k, v in d1.items(): 
    if v in in_both: 
     new_dict.update((k, v)) 
for k, v in d2.items(): 
    if v in in_both: 
     new_dict.update((k, v)) 
print(new_dict)