Unique list (set) to dictionary

烈酒焚心 提交于 2019-12-12 23:50:58

问题


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.


回答1:


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'}



回答2:


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])}



回答3:


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'}


来源:https://stackoverflow.com/questions/17172532/unique-list-set-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!