我有这个数据集。我想更新MySQL表。我可以在当前表单中执行此操作,但我认为转换为字典会缩小列表以进行更新。
我的数据集:
dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
期望的输出:
字典:
output = {'set(['NY'])':121,198,676, 'set(['CA', 'NY'])':132,89}
答案 0 :(得分:5)
您 必须 使用冻结的密钥集。无法保证具有相同元素的集合始终会变为相同的repr
或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)
for value, key in dataset:
output[frozenset(key)].append(value)
或使用已排序的元组
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)
for value, key in dataset:
output[tuple(sorted(key))].append(value)
随机举例来说明这个
>>> 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
答案 1 :(得分:2)
我认为你不能将set
作为字典键,所以也许是一个元组?
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)
for value, key in dataset:
output[tuple(key)].append(value)
# or output[str(key)].append(value) if you want a string as the key
答案 2 :(得分:1)
试试这个:
dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
from collections import defaultdict
d = defaultdict(list)
for val, key in dataset:
d[repr(key)].append(int(val))
d
> {"set(['NY', 'CA'])": [132, 89], "set(['NY'])": [121, 198, 676]}
答案 3 :(得分:1)
以下是defaultdict
的替代方法:
dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
output = {}
for value, key in dataset:
output.setdefault(frozenset(key), []).append(value)
结果:
>>> output
{frozenset(['NY', 'CA']): ['132', '89'], frozenset(['NY']): ['121', '198', '676']}
由于以下行为,我更倾向于使用setdefault()
而不是defaultdict
:
>>> output = defaultdict(list, {frozenset(['NY', 'CA']): ['132', '89'], frozenset(['NY']): ['121', '198', '676']})
>>> output[frozenset(['FL'])] # instead of a key error, this modifies output
[]
>>> output
defaultdict(<type 'list'>, {frozenset(['NY', 'CA']): ['132', '89'], frozenset(['FL']): [], frozenset(['NY']): ['121', '198', '676']})