I'm trying a long time to remove duplicate from a list and create a dictionary with keys like php (0,1,2....).
I have tried :
ids = dict(set([1,2,2,2,3,4,5,4,5,6]))
print ids
Then I want to
for key, value in ids.iteritems():
#stuff
Of course I get the following error because ids is not a dictionary:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Thanks!
Edit:
I think my data was a bit misleading:
I have a list: [foo, bar, foobar, barfoo, foo, foo, bar]
and I want to convert it to: { 1: 'foo', 2 : 'bar', 3 : 'foobar', 4: 'barfoo'}
I don't mind about shorting.
To turn your set of values into a dictionary with ordered 'keys' picked from a sequence, use a
defaultdict
with counter to assign keys:This assigns numbers (starting at 1) as keys to the values in your inputlist, on a first-come first-serve basis.
Demo:
You may use zip for this.
Sample code
If you want to start the key with 0, then Aya's soultion is better.
Not sure what you intend to be the values associated with each key from the
set
.You could use a comprehension: