如何跳过附加到类型列表的dict值的重复值

时间:2012-04-17 09:36:45

标签: python dictionary

实际上我有这种类型的词典

d={'a':{'s':'100100.sss','s1':'100200.ss2','s2':'100200.333'},
  'b':{'t':'100100.yyy','u':'100100.rrr','i':'1001500ttt'},'c':{'f':'g','y':'o'}}

由此我创建了这种类型的词典

temp={'a':['100100','100200','100200'],'b':['100100',100100'],'c'=[]}

为此我正在使用这样的代码

temp={}
for k,v in d.items():
    temp[k]=[]
    for key,val in v.items():
    templist=val.split(".")
    if templist[0].isdigit():
            if templist[0] not in a.values():
                temp[k].append(templist[0])
            else:
                continue

其实我想要这种类型的词典

temp={'a':['100100','100200'],'b':['100100'],'c'=[]}

4 个答案:

答案 0 :(得分:2)

d={'a':{'s':'100100.sss','s1':'100200.ss2','s2':'100200.333'},
  'b':{'t':'100100.yyy','u':'100100.rrr'}}

temp = dict([(k, list(set([x.split('.')[0] for x in v.values()]))) \
       for k,v in d.items()])

解释它的作用。它迭代d中的所有项目,给出键/值对。每个值都是字典,您可以忽略键,因此它会迭代值。这些通过分裂。结果列表将转换为set,这会使值唯一,然后返回列表(不确定您是否确实需要该步骤)。最后,键,值对列表将转换回字典。

答案 1 :(得分:2)

temp = {}
for k,v in d.items():
    for key,val in v.items():
        fn = val.split('.')[0]
        if fn.isdigit():
            temp.setdefault(k, set()).add(fn)
print dict((k, list(v)) for k, v in temp.items())

打印

{'a': ['100100', '100200'], 'b': ['100100']}

或作为单行:

dict((k, list(set(e.split('.')[0] for e in v.values() if e.split('.')[0].isdigit()))) for k,v in d.items())

答案 2 :(得分:1)

仅适用于Python 2.7+3+

>>> d = {'a': {'s': '100100.sss', 's1': '100200.ss2', 's2': '100200.333'},
         'b': {'t': '100100.yyy', 'u': '100100.rrr'}}
>>> {k:{el.split('.')[0] for el in v.itervalues()} for k,v in d.iteritems()}
{'a': set(['100100', '100200']), 'b': set(['100100'])}

答案 3 :(得分:0)

以下是您在IDLE中解决问题的解决方案。人为打破输出以避免滚动。

{k: list(set([i.split('.')[0] for i in v.values()])) for k, v in d.iteritems()}

{'a': ['100100', '100200'], 
 'b': ['100100']}{'a': ['100100', '100200'], 
 'c': ['g', 'o'], 
 'b': ['100100', '1001500ttt']}