简体   繁体   中英

return value if key already in dictionary

I'm currently working on my final assignment for a compsci course. The basic idea is to create a simple encryption program. It uses a file input containing a lines of the alphabet mapped to different letters (ie z to a, y to b, w to c etc) and creates two dictionaries (encoding and decoding) to be used later on and returns 0. The function also needs to test for different problems that may arise and return a different value. The part I'm stuck on is if the key or value has already been added to the dictionary, to return 3 or 4 respectively.

encoding = {}
decoding = {}
def createDictionaries(filepath):
    global encoding
    global decoding
    try:
        with open(filepath) as f:
            for line in f:
                try:
                    (key, val) = line.split()
                except ValueError:
                    return 2
                encoding[(key)] = val
                decoding[(val)] = key
            return 0

    except FileNotFoundError:
        return 1


print(createDictionaries("dict1.txt"))

I've played around with trying to use for loops and exception catching but can't seem to crack it

Any help greatly appreciated.

To check if a key or a value is in a dictionary you can use if key in dic.keys(): and if value in dic.values():

You can add an if statement right before adding the key and value into the dictionaries:

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM