擅长:python、mysql、java
<p>可以在将键和值添加到字典之前添加if语句:</p>
<pre><code>encoding = {}
decoding = {}
def createDictionaries(filepath):
global encoding, decoding
try:
with open(filepath,'r') as f:
for line in f.readlines():
try:
(key, val) = line.split()
except ValueError:
return 2
if key in encoding.keys(): # If this condition is met, return 3
return 3
if val in encoding.values(): # If this condition is met, return 4
return 4
encoding[key] = val
decoding[val] = key
return 0
except FileNotFoundError:
return 1
print(createDictionaries("dict1.txt"))
</code></pre>