티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Mapping over values in a python dictionary

Python 사전(dictionary)에서 값에 대해 매핑(mapping)하는 방법

 문제 내용 

Given a dictionary { k1: v1, k2: v2 ... } I want to get { k1: f(v1), k2: f(v2) ... } provided I pass a function f.

{ k1: v1, k2: v2 ... } 형식의 사전(dictionary)이 주어졌을 때, 함수 f를 전달하면 { k1: f(v1), k2: f(v2) ... } 형식의 결과를 얻으려고 합니다.

 

Is there any such built in function? Or do I have to do

이러한 기능을 수행하는 내장 함수가 있을까요? 아니면 직접 구현해야 할까요?
dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()])

 

Ideally I would just write

이렇게 작성하면 좋겠지만
my_dictionary.map_values(f)

 

or

또는
my_dictionary.mutate_values_with(f)

 

That is, it doesn't matter to me if the original dictionary is mutated or a copy is created.

즉, 원본 사전이 변경되거나 복사본이 생성되는 것은 중요하지 않습니다.

 

 

 

 높은 점수를 받은 Solution 

There is no such function; the easiest way to do this is to use a dict comprehension:

Python에서는 이러한 함수가 내장되어 있지 않습니다. 가장 간단한 방법은 사전 내포(dict comprehension)를 사용하는 것입니다.
my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

 

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

Python 2.7 이전 버전에서는 메모리를 절약하기 위해 .items() 대신 .iteritems() 메소드를 사용해야 합니다. 사전 내포 구문은 Python 2.7에서 소개되었습니다.

 

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

리스트에도 이러한 메소드가 없으므로, 리스트 내포(list comprehension) 또는 map() 함수를 사용해야 합니다.

 

As such, you could use the map() function for processing your dict as well:

따라서 다음과 같이 dict를 처리하기 위해 map() 함수를 사용할 수 있습니다:
my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))

 

but that's not that readable, really.

하지만 그건 가독성이 떨어집니다, 정말로요.

 

 

 

 가장 최근 달린 Solution 

To avoid doing indexing from inside lambda, like:

람다(lambda) 안에서 인덱싱(indexing)을 수행하는 것을 피하기 위해 다음과 같이 작성할 수도 있습니다:
rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))

 

You can also do:

다음 작업도 수행할 수 있습니다:
rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))

 

 

출처 : https://stackoverflow.com/questions/12229064/mapping-over-values-in-a-python-dictionary

반응형
댓글
공지사항
최근에 올라온 글