字典的唯一列表(设置) [英] Unique list (set) to dictionary

查看:93
本文介绍了字典的唯一列表(设置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很长时间试图从列表中删除重复项,并使用php(0,1,2 ....)之类的键创建字典.

I'm trying a long time to remove duplicate from a list and create a dictionary with keys like php (0,1,2....).

我尝试过:

ids = dict(set([1,2,2,2,3,4,5,4,5,6]))
print ids

然后我想

for key, value in ids.iteritems():
     #stuff

我当然会遇到以下错误,因为id不是字典:

Of course I get the following error because ids is not a dictionary:

TypeError: cannot convert dictionary update sequence element #0 to a sequence

谢谢!

我认为我的数据有点误导:

I think my data was a bit misleading:

我有一个列表:[foo, bar, foobar, barfoo, foo, foo, bar]

,我想将其转换为:{ 1: 'foo', 2 : 'bar', 3 : 'foobar', 4: 'barfoo'}

我不介意做空.

推荐答案

要将您的一组值转换成具有从序列中选取的有序键"的字典,请使用带有计数器的defaultdict来分配键:

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}

这将根据先到先得的原则为输入列表中的值分配数字(从1开始)作为键.

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

演示:

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

这篇关于字典的唯一列表(设置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆