티스토리 뷰

반응형

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

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

 

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

Iterating over dictionaries using 'for' loops

'for' 루프를 사용하여 Dictionary에서 반복하기

 문제 내용 

d = {'x': 1, 'y': 2, 'z': 3}

for key in d:
    print(key, 'corresponds to', d[key])

How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is it simply a variable?

파이썬은 사전에서 키만 읽으면 된다는 것을 어떻게 인식하는가? 키는 특별한 키워드인가요, 아니면 단순히 변수인가요?

 

 

 

 높은 점수를 받은 Solution 

key is just a variable name.

키는 변수 이름일 뿐입니다.
for key in d:

 

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

키와 값이 아닌 사전의 키 위에 간단히 루프합니다. 키와 값을 모두 루프하려면 다음을 사용할 수 있습니다.

 

For Python 3.x:

Python 3.x의 경우:
for key, value in d.items():

 

For Python 2.x:

Python 2.x의 경우:
for key, value in d.iteritems():

 

To test for yourself, change the word key to poop.

직접 테스트하려면 단어 키를 똥으로 변경하십시오.

 

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

파이썬 3.x에서 iteritems()은 단순히 items()으로 대체되었으며, 이는 iteritems()과 같이 딕트가 지원하는 집합과 같은 보기를 반환하지만 훨씬 더 좋다. 이것은 2.7에서도 viewitems()으로 사용할 수 있습니다.

 

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

 items()은 2와 3 모두에서 작동하지만 2에서는 사전의 (키, 값) 쌍 목록을 반환하며, 이 목록은 items() 호출 후에 발생하는 딕트의 변경 사항을 반영하지 않습니다. 3.x에서 2.x 동작을 수행하려면 list(d.items())를 호출할 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

For Iterating through dictionaries, The below code can be used.

Dictionaries을 통한 반복에는 아래 코드를 사용할 수 있습니다.

 

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
    print(key)

#To Iterate over the values
for value in dictionary.values():
    print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
    print(key,'\t', value)

 

 

출처 : https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops

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