Python 当值为列表且项不唯一时,交换字典键和值
设置 我有一个大字典,在列表中有唯一键、唯一值和非唯一值 字典看起来像Python 当值为列表且项不唯一时,交换字典键和值,python,dictionary,key,Python,Dictionary,Key,设置 我有一个大字典,在列表中有唯一键、唯一值和非唯一值 字典看起来像 d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']} 问题 我想交换键和值,这样 d_inverse = {'1': ['a', 'b', 'c'], '2': ['a'],'3': ['a', 'c']} 我找到了以下关于交换键和值的答案 关于使用列表中的值交换键 最后一个答案很接近,但不管理列表中的非唯一值 就是 {k: oldk for oldk, ol
d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']}
问题 我想交换键和值,这样
d_inverse = {'1': ['a', 'b', 'c'], '2': ['a'],'3': ['a', 'c']}
我找到了以下关于交换键和值的答案
{k: oldk for oldk, oldv in d.items() for k in oldv}
产生
{'1': 'c', '2': 'a', '3': 'c'}
如何解释非唯一值并不丢失信息?使用
for循环
d = {'a': ['1','2','3'],'b': [1],'c': ['1','3']}
res = {}
for k,v in d.items(): #Iterate dictionary.
for i in v: #Iterate List
i = str(i) #Convert element to string
if i not in res: #Check if key in dictionary.
res[i] = [k]
else:
res[i].append(k) #Else append element.
print(res)
输出:
{'1': ['a', 'c', 'b'], '3': ['a', 'c'], '2': ['a']}
有人回答了这个问题 只需一点小小的改动,它就能按我们的要求工作:
d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']}
inv_map = {}
for k, vs in d.items():
for v in vs:
inv_map.setdefault(v, []).append(k)
print(inv_map)
>>> {'1': ['a', 'b', 'c'], '2': ['a'], '3': ['a', 'c']}
一种方法是使用:
您还可以使用字典理解:
from string import ascii_lowercase as alphabet
d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']}
new_d = {str(alphabet.index(a)+1):[alphabet[int(i)-1] for i in b] for a, b in d.items()}
输出:
{'1': ['a', 'b', 'c'], '2': ['a'], '3': ['a', 'c']}
注意使用循环。注意,在代码< d>代码>列表中,你既有代码< int >代码>代码>字符串值,所以你的输出不太正确(它应该同时具有<代码> 1′<代码>和<代码> 1代码/>键)。谢谢,我编辑了我的例子。谢谢MaARTEN。我找到了那个,但不起作用<代码>列表不可散列。
from string import ascii_lowercase as alphabet
d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']}
new_d = {str(alphabet.index(a)+1):[alphabet[int(i)-1] for i in b] for a, b in d.items()}
{'1': ['a', 'b', 'c'], '2': ['a'], '3': ['a', 'c']}