# Creating an 'if' statement based on the position of a value in a dictionary

765 views
-2

I want to construct some `if` statements based on a particular position in a multi-value dictionary. My example dictionary and pseudocode are:

``````position1 = 0
position2 = 0
position1Unique = 0

exDict = {1: [800, 3, 0, 0], 2: [600, 0, 2, 1], 3: [900, 1, 5, 9]}

for value in exDict:
if value_position1 > 0:
position1 += 1
if value_position2 > 0:
position2 += 1
if value_position1 > 0 AND value_position2 = 0 AND value_position3 = 0:
position1Unique =+ 1
``````

For this dictionary, my values would be:

``````position1 = 2
position2 = 2
position1Unique = 1
``````

If it's not clear from the examples, the key/index and 0th-indexed value don't come into any calculations.

You'll need to rephrase this and rewrite some of the code to be clear about what the variable are meant to be, at the moment it's not clear what value_positionX or position1Unique signify

7

You can iterate over the values of a dictionary with `dict.values`. The values in `exDict` are ordinary lists, and you can index them with `[idx]` just like any other list.

``````position1 = 0
position2 = 0
position1Unique = 0

exDict = {1: [800, 3, 0, 0], 2: [600, 0, 2, 1], 3: [900, 1, 5, 9]}

for value in exDict.values():
if value > 0:
position1 += 1
if value > 0:
position2 += 1
if value > 0 and value == 0 and value == 0:
position1Unique =+ 1

print(position1)
print(position2)
print(position1Unique)
``````

Result:

``````2
2
1
``````

posted this