IT/Python

Python List의 Dictionary 데이터 쉽게 가져오기(Generator Expressions)

반응형

Intro

python의 Boto3를 사용하여 AWS의 리소스들을 출력해보면 대부분 List 안에 Dictionary로 구성 되어있습니다. 따라서 리스트 안에 특정 Value의 데이터를 잘 가져와야 합니다. 오늘은 Python의 Generator Expressions를 사용하여 List안에 있는 Dictionary 데이터를 쉽게 가져올 수 있는 방법을 알아보도록 하겠습니다.

테스트 사이트

해당 사이트에서는 다양한 언어를 실행하여 결과를 확인해볼 수 있습니다.
https://replit.com/

Dictionary List에서 데이터 쉽게 가져오기

list = [ {'Name': 'Tom', 'Age': 30}, {'Name': 'Jack', 'Age': 31}, {'Name': 'Sue', 'Age': 32} ]

## ---------------- Using Generator Expressions ------------
print("Test1") 
tom = (item for item in list if item['Name'] == "Tom")
dict = next(tom, False)
print(dict['Age'])

print("Test2")
tom = (item for item in list if item['Age'] == 30)
dict = next(tom, False)
print(dict['Name'])


## ---------------- Not Using Generator Expressions ------------
print("Test3")
cnt = 0
for item in list :
  cnt += 1
  if item["Name"] == "Tom" :
    break
print(list[cnt-1]["Age"])

print("Test4")
cnt = 0
for item in list :
  cnt += 1
  if item["Age"] == 30 :
    break
print(list[cnt-1]["Name"])
반응형