python - Get dictionary pairs for same items from a list -


i want save same items list (there 2 same items) pairs dictionary. duplicates not supposed appear in dictionary. code:

def find_pairs(list):     dic = {}     if list:         i, obj in enumerate(list, start=0):             if obj not in dic:                 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'}} 

is there better way of doing this?

maybe wasn’t clear enough on trying do. in fact have list of objects identifiers. objects identifier can access object name return string. need pair objects sector of string matches object list. did here:

def find_pairs(list):     dic = {}     if list:         i, obj in enumerate(list, start=0):             if obj not in dic:                 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) 

i amateur programmer troubling implement in more clever way.

you can use collections.defaultdict:

from collections import defaultdict  d = defaultdict(set) mylist = ["ae","e","w","b","d","c","ae","w","d","e","c","b"] in mylist:     d[i].add(i)  print(dict(d)) 

output:

{'d': {'d'}, 'e': {'e'}, 'b': {'b'}, 'ae': {'ae'}, 'w': {'w'}, 'c': {'c'}} 

or, shorter way:

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

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -