简体   繁体   中英

Unique list (set) to dictionary

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:

from collections import defaultdict
from itertools import count
from functools import partial

keymapping = defaultdict(partial(next, count(1)))
outputdict = {keymapping[v]: v for v in inputlist}

This assigns numbers (starting at 1) as keys to the values in your inputlist, on a first-come first-serve basis.

Demo:

>>> from collections import defaultdict
>>> from itertools import count
>>> from functools import partial
>>> inputlist = ['foo', 'bar', 'foobar', 'barfoo', 'foo', 'foo', 'bar']
>>> keymapping = defaultdict(partial(next, count(1)))
>>> {keymapping[v]: v for v in inputlist}
{1: 'foo', 2: 'bar', 3: 'foobar', 4: 'barfoo'}

Not sure what you intend to be the values associated with each key from the set .

You could use a comprehension:

ids = {x: 0 for x in set([1,2,2,2,3,4,5,4,5,6])}

You may use zip for this.

Sample code

>>> ids
['foo', 'bar', 'foobar', 'barfoo', 'foo', 'foo', 'bar']
>>> dict(zip(range(1,len(ids)+1), sorted(set(ids))))
{1: 'bar', 2: 'barfoo', 3: 'foo', 4: 'foobar'}
>>>

If you want to start the key with 0, then Aya's soultion is better.

>>> ids
['foo', 'bar', 'foobar', 'barfoo', 'foo', 'foo', 'bar']
>>> dict(enumerate(sorted(set(ids))))
{0: 'bar', 1: 'barfoo', 2: 'foo', 3: 'foobar'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM