2017-03-22 31 views
-1

我必須顛倒字典中的鍵和值,但它不考慮整個字符串,它會考慮字符。Python:在字典中反向鍵和值考慮字符串而不是字符

我的代碼如下:

locat= {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'} 
location = {} 
for e, char in locat.items(): 
     location.setdefault(char, []).append(e) 

我的結果:

{'aa': [1, 1], 'ab': [2, 4, 2, 4], 'ba': [3]} 

但我期待這樣的結果:

{'aa': [1], 'ab': [2, 4], 'ba':[3]} 

預先感謝您。

問候,

+0

值請提供補碼(LOCATION2)不粘貼代碼的一部分。 – srj

+2

不要使用字典作爲變量 – abccd

+0

'dict'應該是'locat'嗎?如果是這樣,你的代碼是正確的,並在Python 2和Python 3上正常工作。 –

回答

2

試試這個:

c={} 
dict = {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'} 
for e, char in dict.items(): 
    c.setdefault(char, []).append(e) 

print(c) 

輸出:

{'aa': [1], 'ab': [2, 4], 'ba': [3]} 

或者

from collections import defaultdict 

c = defaultdict(list) 
dict = {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'} 
for e, char in dict.items(): 
    c[char] += [e] 
print(c) 

輸出:

defaultdict(<class 'list'>, {'aa': [1], 'ab': [2, 4], 'ba': [3]}) 

defaultdict與dict:

python3.x可以使用

import builtins 
print(builtins.dict(c)) 

的Python 2.x的試試這個:

import __builtin__ 
print(__builtin__.dict(c)) 

順便說一下,請不要使用字典作爲變量。

+0

謝謝,我怎樣才能訪問只有字典沒有defaultdict ... – Amy21

+0

@ Amy21我更新了我的答案,看看。 – McGrady

1

你可以這樣說:

location = {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'} 
location_new={} 
for i,s in location.items(): 
    if s in location_new: 
     location_new[s]+=[i] 
    else: 
     location_new[s]=[i] 
print(location_new) 

輸出:

{'aa': [1], 'ab': [2, 4], 'ba': [3]} 

餘項: 不要使用dictlist或任何其他類型的變量,它會事業錯誤稍後的。

1

使用dict comprehension

{v:[k for k in dict if dict[k] == v] for v in dict.itervalues()} 

我使用列表理解[k for k in dict if dict[k]來計算每個鍵

+0

添加關於代碼的一些解釋將有助於未來用戶理解答案。 – arulmr

+0

@arulmr編輯!!!! –