How do I convert a list of tuples with sets to a dictionary? -


i have dataset. want update mysql table. can in current form thought conversion dictionary shrink list updated.

my dataset :

dataset = [('121', set(['ny'])), ('132', set(['ca', 'ny'])), ('198', set(['ny'])), ('676', set(['ny'])), ('89', set(['ny', 'ca']))] 

desired output :

a dictionary :

output = {'set(['ny'])':121,198,676, 'set(['ca', 'ny'])':132,89} 

you must use frozenset key. there no guarantee set same elements turned same repr or tuple sets unordered. unless sort set elements first of course, seems wasteful

from collections import defaultdict  dataset = [('121', set(['ny'])), ('132', set(['ca', 'ny'])), ('198', set(['ny'])), ('676', set(['ny'])), ('89', set(['ny', 'ca']))] output = defaultdict(list) value, key in dataset:     output[frozenset(key)].append(value) 

or using sorted tuple

from collections import defaultdict  dataset = [('121', set(['ny'])), ('132', set(['ca', 'ny'])), ('198', set(['ny'])), ('676', set(['ny'])), ('89', set(['ny', 'ca']))] output = defaultdict(list) value, key in dataset:     output[tuple(sorted(key))].append(value) 

random example illustrate this

>>> s,t = set([736, 9753, 7126, 7907, 3350]), set([3350, 7907, 7126, 9753, 736]) >>> s == t true >>> tuple(s) == tuple(t) false >>> frozenset(s) == frozenset(t) true >>> hash(tuple(s)) == hash(tuple(t)) false >>> hash(frozenset(s)) == hash(frozenset(t)) true 

Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -