Python/Python

[파이썬] 제어문 5.3 반복문 Loop + 사전형 데이터 Dictionary

JBS 12 2024. 3. 5. 10:03

Dictionary data type 

 

 

왼쪽에

각각의 원소에 이름 붙이기 

 

 

이름과 의미로 이루어짐 

= 사전형 dictionary data type 

 

 

값의 이름 = key 

값 = value 

 

dictionary data가 있을 때, data를 가져올 때 

 

 

person['name'] 

= name이라는 키 값의

   value를 가져오는 것

 

사전형 데이터를 반복문 이용 -> 데이터 하나씩 꺼내기

for문 이용 

for key in person

 

 

person의 key를 하나씩 꺼내서 

key라고 하는 이름의 변수값을 할당

 

각각의 원소의 데이터를 가져올 때

list 이름 안에, key의 이름 넣어주기 

 

 

 

dictionary를 List 안에 담아서 복합적인 데이터 만들기 

1) 원소 하나씩 꺼내오기

 

persons 리스트 안에 

들어있는 원소 

{'name': 'egoing', 'address': 'Seoul', 'interest':'Web'},
{'name': 'basta', 'address': 'Seoul', 'interest':'IOT'},
{'name': 'blackdew', 'address': 'Tongyeong', 'interest':'ML'}​

 

 

하나씩 꺼내오기 

 

persons = [
    {'name': 'egoing', 'address': 'Seoul', 'interest':'Web'},
    {'name': 'basta', 'address': 'Seoul', 'interest':'IOT'},
    {'name': 'blackdew', 'address': 'Tongyeong', 'interest':'ML'}
]

print('=== persons ===')
for person in persons:
    print(person)

 

 

그러면 행마다 실행됨. 

 

2) person으로 들어오는 값에 대한 반복문 실행 (사전형 + 반복문)

person으로 들어오는 값에 대한 

반복문 실행 

for person in persons:
    for key in person:

 

 

 

key와 value값을 보기 좋게 실행 

persons = [
    {'name': 'egoing', 'address': 'Seoul', 'interest':'Web'},
    {'name': 'basta', 'address': 'Seoul', 'interest':'IOT'},
    {'name': 'blackdew', 'address': 'Tongyeong', 'interest':'ML'}
]

print('=== persons ===')
for person in persons:
    for key in person:
        print(key, ':', person[key])

 

 


정리 

 

List: 이름은 필요없고 순서에 따라서 데이터 저장 

Dictionary: 순서는 상관없고 데이터에 이름을 주고 싶을 때