我需要按值对字典键进行分组,并将其放入一个新字典中。我期待这样的内容:
groupedByValue = {'set1':[obj1],'set2':[obj2,obj3,obj6],'set3':[obj5,obj7]}
源代码:
dictionary = {'obj1':(10), 'obj2':(12), 'obj3':(12), 'obj5':(15), 'obj6':(12), 'obj7':(15)}
groupedByValue = {}
字典值周围的()不做任何事情——您可以通过迭代旧字典来创建新字典。
为了更接近你的"想要的"输出您可以使用第二个字典的值->键映射:
dictionary = {'obj1':10, 'obj2':12, 'obj3':12, 'obj5':15, 'obj6':12, 'obj7':15}
groupedByValue = {}
keyVal = {}
i = 0
for key,value in dictionary.items():
# increase i to get a new key for this value else use existing key
if value not in keyVal:
i += 1
# for clarity - could directly do
# groupedByValue.setdefault(keyVal.setdefault(value, f"set{i}"), []).append(key)
kk = keyVal.setdefault(value, f"set{i}")
groupedByValue.setdefault(kk, []).append(key)
print(groupedByValue)
输出:
{'set1': ['obj1'], 'set2': ['obj2', 'obj3', 'obj6'], 'set3': ['obj5', 'obj7']}
没有这种复杂性,您可以应用任何副本的答案来促进分组:
与https://stackoverflow.com/a/15751984/7505395答案部分相似:
dictionary = {'obj1':10, 'obj2':12, 'obj3':12, 'obj5':15, 'obj6':12, 'obj7':15}
groupedByValue = {}
for key,value in dictionary.items():
groupedByValue.setdefault(value,[]).append(key)
print(groupedByValue)
输出:
{10: ['obj1'], 12: ['obj2', 'obj3', 'obj6'], 15: ['obj5', 'obj7']}