본문 바로가기
IT/Python

[Python] json의 key, value에 따른 데이터 추출

by 강천구 2023. 3. 10.

json에서 key값이 실제 값인 경우

user_list = {
    "user1": {
    	"key1" : "Y",
        "key2" : "Y"
    },
    "user2": {
    	"key1" : "N",
        "key2" : "Y"
    },
    "user3": {
    	"key1" : "N",
        "key2" : "N"
    }
}

 

key만 필요한 경우

list = data.keys()
# dict_keys(["user1","user2","user3"])

list = [user for user in data]
# ["user1","user2","user3"]

 

value만 필요한 경우

list = [data.get(user) for user in data]
'''
[
    {
    	"key1" : "Y",
        "key2" : "Y"
    },
    {
    	"key1" : "N",
        "key2" : "Y"
    },
    {
    	"key1" : "N",
        "key2" : "N"
    }
]
'''

 

key1이 N인 유저만 추출하고 싶다면

list = [user for user in data if data[user].get("key1","Y") == "N"]
'''
['user2','user3']
'''

 

반응형

'IT > Python' 카테고리의 다른 글

[Python] Requests timeout 설정  (0) 2023.01.27
[Python] String에 변수 사용(f-string)  (1) 2022.11.13
[Python] 2차원 배열 정렬 방법  (0) 2022.07.31
[Python] "return list.sort()"는 None 일 때  (0) 2022.07.31

댓글