your programing

Python : 사전의 값으로 키를 교환하는 가장 좋은 방법은 무엇입니까?

lovepro 2020. 9. 25. 23:22
반응형

Python : 사전의 값으로 키를 교환하는 가장 좋은 방법은 무엇입니까?


사전을 입력으로 받고 키가 입력 값이되고 해당 값이 해당 입력 키가되는 사전을 반환하고 싶습니다. 값은 고유합니다.

예를 들어, 내 입력은 다음과 같습니다.

a = dict()
a['one']=1
a['two']=2

내 출력은 다음과 같습니다.

{1: 'one', 2: 'two'}

명확히하기 위해 내 결과가 다음과 동일하기를 바랍니다.

res = dict()
res[1] = 'one'
res[2] = 'two'

이것을 달성하는 깔끔한 Pythonian 방법은 무엇입니까?

감사


파이썬 2 :

res = dict((v,k) for k,v in a.iteritems())

Python 3 (@erik에게 감사) :

res = dict((v,k) for k,v in a.items())

new_dict = dict (zip(my_dict.values(),my_dict.keys()))

3.0 이상을 포함하여 Python 2.7부터는 더 짧고 읽기 쉬운 버전이 있습니다.

>>> my_dict = {'x':1, 'y':2, 'z':3}
>>> {v: k for k, v in my_dict.items()}
{1: 'x', 2: 'y', 3: 'z'}

In [1]: my_dict = {'x':1, 'y':2, 'z':3}

In [2]: dict((value, key) for key, value in my_dict.iteritems())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}

dict comprehensions를 사용할 수 있습니다 .

res = {v: k for k, v in a.iteritems()}

편집 됨 : Python 3 a.items()의 경우 a.iteritems(). 그들 사이의 차이점에 대한 토론은 Python의 iteritems on SO 에서 찾을 수 있습니다 .


시도해 볼 수 있습니다.

d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.iteritems())
d2
  {'two': 2, 'one': 1}

다음과 같은 경우 사전을 '반전'할 수 없습니다.

  1. 둘 이상의 키가 동일한 값을 공유합니다. 예를 들면 {'one':1,'two':1}. 새 사전에는 키가있는 항목이 하나만있을 수 있습니다 1.
  2. 하나 이상의 값은 해시 할 수 없습니다. 예를 들면 {'one':[1]}. [1]은 유효한 값이지만 유효한 키가 아닙니다.

주제에 대한 토론은 파이썬 메일 링리스트 에서이 스레드참조하십시오 .


res = dict(zip(a.values(), a.keys()))


new_dict = dict( (my_dict[k], k) for k in my_dict)

또는 더 좋지만 Python 3에서만 작동합니다.

new_dict = { my_dict[k]: k for k in my_dict}

현재 선행 답변은 값이 고유하다고 가정하지만 항상 그런 것은 아닙니다. 값이 고유하지 않으면 어떻게됩니까? 정보를 잃어 버릴 것입니다! 예를 들면 :

d = {'a':3, 'b': 2, 'c': 2} 
{v:k for k,v in d.iteritems()} 

를 반환합니다 {2: 'b', 3: 'a'}.

에 대한 정보 'c'는 완전히 무시되었습니다. 이상적으로는 {2: ['b','c'], 3: ['a']}. 이것이 하단 구현이하는 일입니다.

def reverse_non_unique_mapping(d):
    dinv = {}
    for k, v in d.iteritems():
        if v in dinv:
            dinv[v].append(k)
        else:
            dinv[v] = [k]
    return dinv

Another way to expand on Ilya Prokin's response is to actually use the reversed function.

dict(map(reversed, my_dict.items()))

In essence, your dictionary is iterated through (using .items()) where each item is a key/value pair, and those items are swapped with the reversed function. When this is passed to the dict constructor, it turns them into value/key pairs which is what you want.


Suggestion for an improvement for Javier answer :

dict(zip(d.values(),d))

Instead of d.keys() you can write just d, because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.

Ex. for this behavior :

d = {'a':1,'b':2}
for k in d:
 k
'a'
'b'

Can be done easily with dictionary comprehension:

{d[i]:i for i in d}

dict(map(lambda x: x[::-1], YourDict.items()))

.items() returns a list of tuples of (key, value). map() goes through elements of the list and applies lambda x:[::-1] to each its element (tuple) to reverse it, so each tuple becomes (value, key) in the new list spitted out of map. Finally, dict() makes a dict from the new list.


Using loop:-

newdict = {} #Will contain reversed key:value pairs.

for key, value in zip(my_dict.keys(), my_dict.values()):
    # Operations on key/value can also be performed.
    newdict[value] = key

If you're using Python3, it's slightly different:

res = dict((v,k) for k,v in a.items())

Adding an in-place solution:

>>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> for k in list(d.keys()):
...     d[d.pop(k)] = k
... 
>>> d
{'two': 2, 'one': 1, 'four': 4, 'three': 3}

In Python3, it is critical that you use list(d.keys()) because dict.keys returns a view of the keys. If you are using Python2, d.keys() is enough.

참고URL : https://stackoverflow.com/questions/1031851/python-best-way-to-exchange-keys-with-values-in-a-dictionary

반응형