Reputation: 23
The problem is to write a Python function that returns a list of keys in aDict with the value target. All keys and values in the dictionary are integers and the keys in the list we return must be in increasing order.
This is the work I have so far:
def keysWithValue(aDict, target):
'''
aDict: a dictionary
target: an integer
'''
ans = []
if target not in aDict.values():
return ans
else:
for key in aDict.keys():
if target in aDict[key]:
ans+=[key]
return ans.sort()
I keep on getting:
"TypeError: argument of type 'int' is not iterable"
but I don't really understand what that means, and how to fix it. If anyone could help, I'd be really grateful!
Upvotes: 2
Views: 4707
Reputation: 1
def keysWithValue(aDict, target):
'''
aDict: a dictionary
target: an integer
'''
ans = []
if target not in aDict.values():
return ans
else:
for key in aDict.keys():
if target == aDict[key]:
ans.append(key)
ans.sort()
return ans
//This will do your task. :)
Upvotes: 0
Reputation: 3560
When you are doing
if target in aDict[key]
You are basically checking if target is in some sort of array, but aDict[key] is not an array, it is an integer! You want to check if target is equal to aDict[key], not if it is contained by aDict[key].
Hence, do
if target == aDict[key]
Iteration is when you access every element of a collection one by one. However, an integer is not a collection, it is a number!
Upvotes: 0
Reputation: 2499
Your aDict[key]
is an int and therefor is not iterable, ie you cannot use if target in aDict[key]:
you will have to change the values to strings.
if str(target) in str(aDict[key])
or
if target == aDict[key]
Although the second option will have to be an exact match. It is unclear on what you a specifically after
Upvotes: 0
Reputation: 21619
The issue is here
if target in aDict[key]:
You are trying to iterate over an integer value, which wont work.
You should instead use
if target == aDict[key]:
You can refactor your code like this. I have made an assumption about what your input data looks like. If I'm wrong I can adjust my answer.
d = {1:1, 2:2, 3:3, 4:3, 5:3}
def keysWithValue(aDict, target):
ans = []
#for k, v in aDict.iteritems():
for k, v in aDict.items():
if v == target:
ans.append(k)
return sorted(ans)
print(keysWithValue(d, 3))
The commented line is what should be used for python 2.x instead of the line below it.
Upvotes: 1