Your for-loop recreates the whole dict() on every iteration: dict = {i[0]:i}
-leaving you with the last value.
Your (working) implementation would make this
print setdict(["hello", "world", "something", "foo", "hello - 2"])
to
{"h":"hello - 2", "w":"world", "s":"something", "f":"foo"}
loosing the first "hello"
.
It may be better to use a defaultdict to avoid overwriting duplicates:
from collections import defaultdict
def setdict(l): # dont do l = [] - it has ramifications
d = defaultdict(list)
for i in l:
d[i[0]].append(i)
return dict(d)
print setdict(["hello", "world", "something", "foo", "hello - 2"])
Output:
{'h': ['hello', 'hello - 2'], 's': ['something'], 'w': ['world'], 'f': ['foo']}
Other remarks & ramifications:
do not call variables after built ins - they shadow them:
k = str(5)
str = 22
o = str(5) # crash - the str-function is shadowed
avoid default params that are references:
def k(l=[]): # reference default param, keeps values
l.append(0) # over different calls of the function
return l
print(k())
print(k())
print(k())
print(k())
print(k())
[0]
[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]
See "Least Astonishment" and the Mutable Default Argument