【发布时间】:2014-02-17 22:54:12
【问题描述】:
我有一本这样的字典:
dict1 = {'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]}
并且想要这样的逆:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
喜欢这些问题:
Inverse Dict in Python \\ In-place dictionary inversion in Python
但我想用非唯一键来做,我不想就地转换。我有一些代码在工作,但我想知道是否有一种字典理解方式可以做到这一点。
from collections import defaultdict
dict2 = defaultdict(list)
for i in dict1:
for j in dict1[i]:
dict2[j].append(i)
我试过这个,但它只适用于独特的映射。唯一我的意思是“对于每个值,只有一个键在其下列出该值”。所以唯一映射:'1:[a],2:[b],3:[c] -> a:[1],b:[2],c:[3]'VS非唯一映射'1: [a], 2: [a, b], 3: [b, c] -> a: [1, 2], b: [2, 3], c: [3]'
dict2 = {j: i for i in dict1 for j in dict1[i]}
我想一定是这样的:
dict2 = {j: [i for i in dict1 if j in dict1[i]] for j in dict1[i]} # I know this doesn't work
除了它不起作用之外,这样的理解似乎效率低下。有没有一种有效的、单一的方式来做到这一点?
【问题讨论】:
-
它不适用于非唯一值,根据定义,字典或哈希表中的键是唯一的
-
Python 字典不支持重复键 -->
http://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python -
我猜我对“独特”的使用是模棱两可的。我所说的“唯一”的意思是,如果原始字典具有从键-> 值的 1-1 映射。唯一我的意思是“对于每个值,只有一个键列出了该值”。如此独特的映射:
'1: [a], 2: [b], 3: [c] -> a: [1], b: [2], c: [3]' vs '1: [a], 2: [a, b], 3: [b, c] -> a: [1, 2], b: [2, 3], c: [3]' -
"...这样的理解似乎效率低下。"似乎您正试图过早地优化您的代码。使用显式
for循环可能不会对代码的性能产生重大影响。 -
您到底想对重复项做什么?丢弃它们?将它们分组到列表中?如果丢弃,你如何定义哪些?
标签: python dictionary dictionary-comprehension