Reputation: 47
From a tuple of strings, a function that creates a dictionary and adds the index (key) and length of string (value). But, the for loop only adds certain entries (in this case indexes 0 and 2) and can't figure out why.
Code:
def check_horse_winner(tup):
results=dict()
for i in tup:
results[tup.index(i)]=len(i)
return results
print(check_horse_winner(("HORSE", "HORSE", "HORS", "HORSE")))
Output:
{0: 5, 2: 4}
Upvotes: 3
Views: 398
Reputation: 56
Dictionary is a mapping of unique keys to values
You are pushing same index in your dict, this line cause the issue "tup.index(i)" because of "HORSE" value it will get the first index for "HORSE".
Try to change the value of your tuple.
anyways you could check https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python/
Upvotes: 2
Reputation: 43
index() method searches for the given element in a tuple and returns its position.
However, if the same element is present more than once, the first/smallest position is returned.
So in your case tup.index("HORSE") returns 0 as its index every time. Since there are only two unique elements in the tuple you passed, the return dict has only 2 key-value pairs
Upvotes: 0
Reputation: 1910
There are same elements in this tuple. index
returns the first element's index - so, your program does this:
i
is "HORSE"
, index
returns 0.i
is "HORSE"
again, index
will return the first occurrence of it, which is 0 again.And this goes all the way - except for "HORS"
(I think it is just a mistake).
The solution:
Loop over indices rather than the tuple itself, like this:
for i in range(len(tup)):
results[i] = len(tup[i])
Upvotes: 0
Reputation: 169397
There are duplicate values in tup
, and .index()
returns the first.
Sounds like you want
words = ("HORSE", "HORSE", "HORS", "HORSE")
index_to_length = {
i: len(w)
for (i, w)
in enumerate(words)
}
print(index_to_length)
Upvotes: 2
Reputation: 13426
tup.index(i)
will always give you index of first entry in tuple.
As you have same element thrice and dict
can not take duplicate keys, it's replacing the same
You can do :
def check_horse_winner(tup):
results=dict()
for i,j in enumerate(tup):
results[i]=len(j)
return results
print(check_horse_winner(("HORSE", "HORSE", "HORS", "HORSE")))
Alternative:
print({j:len(i) for j,i in enumerate(("HORSE", "HORSE", "HORS", "HORSE"))})
Upvotes: 1
Reputation: 82805
Use enumerate
Ex:
def check_horse_winner(tup):
results=dict()
for i, v in enumerate(tup):
results[i]=len(v)
return results
print(check_horse_winner(("HORSE", "HORSE", "HORS", "HORSE")))
# --> {0: 5, 1: 5, 2: 4, 3: 5}
Upvotes: 2