vendredi 3 juin 2016

Dictionary lookup in if statement

I have a dictionary which I am populating with values. The values are served to the dictionary through a for-loop.

storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
index_tracker = 0

for each_element in listholder:
    if index_tracker == 7:
        pass
    else:
        storageDict[str(each_element)] = values[index_tracker]
        index_tracker += 1

print(storageDict)

This gives me the following output:

 {'word5': 'word6', 'word1': 'word1', 'word3': 'word2', 'word4': 'word5', 'word6': 'word7', 'word2': 'word3'}

While all key-value combinations are unique I would like to avoid any scenarios whereby the dictionary contains a key-value combination that is the same as the value-key combination. i.e In the dictionary above we have the following two key-value combinations:

  • 'word3': 'word2'
  • 'word2': 'word3'

I would therefore like to check whether a value-key combination and key-value combination is already in the dictionary before committing it to the dict. I came up with the following code, but PyCharm is giving me an Key error:

storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
index_tracker = 0

for each_element in listholder:
    if index_tracker == 7:
        pass
    else:
        if storageDict[each_element] == values[index_tracker] and storageDict[values[index_tracker]] == each_element:
             pass
        else:
            storageDict[each_element] = values[index_tracker]
            index_tracker += 1

print(storageDict)

My desired output is one for the two scenarios: {'word5': 'word6', 'word1': 'word1', 'word4': 'word5', 'word6': 'word7', 'word2': 'word3'}

or {'word5': 'word6', 'word1': 'word1', 'word3': 'word2', 'word4': 'word5', 'word6': 'word7'}

Here the KeyError:

Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/momely/placementarchitect/testbench.py", line 42, in <module>
if storageDict[each_element] == values[index_tracker] and storageDict[values[index_tracker]] == each_element:
KeyError: 'word1'

I believe I understand why the error occurs. By including my check in the conditional if statement I am requesting the key-value for a dictionary key that doesn't exist yet.

But how would anyone check a key-value then?

I considered working with tuples instead but will require the dictionary's fast loopup in a different operation.

Any advice would be highly appreciated.

Have a great day.

M

Aucun commentaire:

Enregistrer un commentaire