To expand on not_speshal's answer:
What lead to multiple boolean prints?
The issue's in your code are:
- printing in the loop will print for each entry in dict
- not returning, means looping through the complete dictionary
Solving iteratively
You can solve these issues, improve code and learn step by step (iteratively).
1. make it return
# rename from `valueDict` to a question in order to signal boolean return
def hasKeyWithValue(key,value):
for i, j in WaywardSonDict.items():
if i == key and j == value:
return True
# no else, simply continue looping to the end
return False # if not found and returned, finally return False
print(hasKeyWithValue('Genre', 'Hard Rock') # prints: True
Design advice: rename the function to signal expected boolean. This can be done by naming it like a question.
2. use dict's getter function instead of loop
def hasKeyWithValue(key,value):
if WaywardSonDict.get(key) == value:
return True
else:
return False
Then you need a complete if-else.
Alternatively you could substitute the else
by a default return:
def hasKeyWithValue(key,value):
if WaywardSonDict.get(key) == value:
return True # that's the "unexpected"
return False # that's the default
Note: .get
is special here, because it will return None
if the key is not found.
This allows for non-existence checks like hasKeyWithValue('Year',None)
which will return True
because the given dictionary has no entry with key Year
.
3. simplify the if-return
def hasKeyWithValue(key,value):
return (WaywardSonDict.get(key) == value)
Simplify the test. The if-else statement is obsolete, because the boolean expression (inside parentheses) evaluates to either True or False.
4. inline the simple test
key = 'Genre'
value = 'Hard Rock'
print(WaywardSonDict.get(key) == value)
So the hasKeyWithValue
function has been replaced by a short ideomatic dictionary-test (that most Python developers can understand).
5. improve readability
# format like a table to ease reading
WaywardSonDict = {
"Artist" : "Kansas",
"Song" : "Carry on Wayward Son",
"Genre" : "Hard Rock",
"Album" : "Leftoverture",
"Writer" : "Kerry Livgren"
}
This way you can easily scan the dictionary entries like a check-list.