从列表中获取相同项的字典对

时间:2017-08-18 13:43:09

标签: python python-2.7 list dictionary

我想将列表中的相同项目(总是只有2个相同的项目)保存为字典。重复不应出现在字典中。这是我的代码:

def find_pairs(list):
    dic = {}
    if list:
        for i, obj in enumerate(list, start=0):
            if obj not in dic:
                for k in xrange(i+1, len(list)):
                    if obj == list[k]:
                        dic[obj] = {list[k]}
    return dic

mylist = ["AE","E","W","B","D","C","AE","W","D","E","C","B"]
res = find_pairs(list)
print(res)  # {'W': {'W'}, 'E': {'E'}, 'C': {'C'}, 'D': {'D'}, 'B': {'B'}, 'AE': {'AE'}}

有更好的方法吗?

也许我对自己要做的事情不够清楚。实际上我有一个对象标识符列表。使用此对象标识符,我可以访问将作为字符串返回的对象名称。现在我需要将字符串的某个扇区与列表中的另一个对象匹配的对象配对。正如我在这里所做的那样:

def find_pairs(list):
    dic = {}
    if list:
        for i, obj in enumerate(list, start=0):
            if obj not in dic:
                for k in xrange(i+1, len(list)):
                    if return_keyvalue(rs.ObjectName(obj), "_", 4) == return_keyvalue(rs.ObjectName(list[k]), "_", 4):
                        dic[obj] = list[k]
    return(dic)

我只是一名业余程序员,所以我很难以更聪明的方式实现这一点。

1 个答案:

答案 0 :(得分:0)

您可以使用collections.defaultdict

from collections import defaultdict

d = defaultdict(set)
mylist = ["AE","E","W","B","D","C","AE","W","D","E","C","B"]
for i in mylist:
    d[i].add(i)

print(dict(d))

输出:

{'D': {'D'}, 'E': {'E'}, 'B': {'B'}, 'AE': {'AE'}, 'W': {'W'}, 'C': {'C'}}

或者,更短的方式:

d = {i:set(i) for i in mylist}