티스토리 뷰

반응형

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

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

 

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

How to check if a variable is a dictionary in Python?

Python에서 변수가 dictionary인지 확인하는 방법은 무엇인가요?

 문제 내용 

How would you check if a variable is a dictionary in Python?

파이썬에서 변수가 딕셔너리인지 어떻게 확인할 수 있나요?

 

For example, I'd like it to loop through the values in the dictionary until it finds a dictionary. Then, loop through the one it finds:

예를 들어, 딕셔너리의 값들을 반복문으로 탐색하다가 딕셔너리를 찾을 때까지 계속 반복하고 싶다면 어떻게 해야 할까요?
dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for k, v in dict.iteritems():
    if ###check if v is a dictionary:
        for k, v in v.iteritems():
            print(k, ' ', v)
    else:
        print(k, ' ', v)

 

 

 높은 점수를 받은 Solution 

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

ele이 딕셔너리인지 확인하는 방법으로는, type(ele) is dict 혹은 isinstance(ele, dict)를 사용할 수 있습니다. 만약 딕셔너리를 subclass하였다면 isinstance(ele, dict)를 사용하는 것이 더 적절합니다.
d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k,' ',v)

 

 

 가장 최근 달린 Solution 

My testing has found this to work now we have type hints:

파이썬의 타입 힌트(type hints)를 사용할 수 있는 버전에서 이 코드가 작동합니다.
from typing import Dict

if isinstance(my_dict, Dict):
    # True
else:
    # False

 

Side note some discussion about typing.Dict here

참고로 typing.Dict에 대한 논의는 여기에서 확인할 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/25231989/how-to-check-if-a-variable-is-a-dictionary-in-python

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