python 질문드립니다.
본문
안녕하세요.
python 아래와 같이 data 있습니다.
writers":[{"id":358700,"name":"오징어"},{"id":358701,"name":"꼴뚜기"},{"id":366531,"name":"가물치"}],"painters":[{"id":358702,"name":"그림판"}]
writers_id = content['writers'][0]['id'] => 358700
writers_name = content['writers'][0]['name'] => 오징어
이렇게 첫번째 데이터를 잘 가지고 옵니다.
그런데 writers 3개(몇개가 될지 알수없음)가 있으므로 반복문을 돌려서 콤마로 구분할수 있을까요?
writers_id = 358700,358701,366531
writers_name = 오징어,꼴뚜기,가물치
감사합니다.
답변 2
content={
"writers":[{"id":358700,"name":"오징어"},{"id":358701,"name":"꼴뚜기"},{"id":366531,"name":"가물치"}],"painters":[{"id":358702,"name":"그림판"}]
}
writers_id = []
writers_name = []
for i in content['writers']:
writers_id.append(i['id'])
writers_name.append(i['name'])
writers_id = ','.join(map(str, writers_id))
writers_name = ','.join(map(str, writers_name))
print('writers_id:', writers_id)
print('writers_name:', writers_name)
다음과 같은 방법도 있으니 참고해 보세요
data = {
"writers": [
{"id": 358700, "name": "오징어"},
{"id": 358701, "name": "꼴뚜기"},
{"id": 366531, "name": "가물치"}
],
"painters": [
{"id": 358702, "name": "그림판"}
]
}
writers_ids = []
writers_names = []
for writer in data.get("writers", []):
writers_ids.append(str(writer["id"]))
writers_names.append(writer["name"])
writers_id = ",".join(writers_ids)
writers_name = ",".join(writers_names)
print("writers_id:", writers_id)
print("writers_name:", writers_name)
!-->
답변을 작성하시기 전에 로그인 해주세요.