簡體   English   中英

在Python中的字典中交換鍵以獲取唯一值

[英]Swap keys for unique values in a dictionary in Python

a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = {}
for key, val in a.items():
    b[val] = key
print b

我想做的是將字典的值交換為密鑰。 但是使用此代碼,我丟失了字典的一些信息,得到了以下輸出:

{'LinMotion': 10, 'PtpMotion': 9, 'Wait': 11}

為什么會發生?

每個密鑰在字典中只能出現一次。 您可以存儲每個鍵的索引列表:

import collections
b = collections.defaultdict(list)
for key, val in a.iteritems():
    b[val].append(key)
print b
# {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]}

編輯:正如ecik在評論中指出的那樣,您還可以使用defaultdict(set) (並在循環中使用.add()而不是.append() )。

當你說

b[val] = key

並且val已經存在,它將覆蓋設置,得到您所看到的。 要獲取所有值,必須將原始值映射到鍵列表,例如

from collections import defaultdict

b = defaultdict(list)
for key, val in a.items():
    b[val].append(key)
print b

當我這樣做(python 2.5.1)時,我得到

defaultdict(<type 'list'>, {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 
                            'PtpMotion': [0, 1, 9], 
                            'Wait': [11]})

字典鍵必須唯一。 如果要保留它們,則必須將b[val]的每個值都設為一個列表,然后將這些值添加到這些列表中。

也許您想要輸出字典中的列表:

from collections import defaultdict
a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = defaultdict(list)
for key, val in a.items():
    b[val].append(key)
print b

產量:

defaultdict(<type 'list'>, {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM