본문 바로가기
Data Science

[Python] Dictionary

by kimpackung 2021. 8. 8.
728x90

Dictionary

 

1) key- value pair

2) Using curly bracket

3) Items are ordered (as of python version 3.7)

4) keys have to be unique

 

키와 값을 짝지어서 저장할 때 유용하지만,

작업이 비효율적일 수 있음

 

 

<Code>

 

1)creating a new dictionary and inserting keys values.

#creating new dictionary
dic=dict() # or dic={}
print(dic)

#creating a dictionary with only keys
k=["a","b","c"]
dic2 = dict.fromkeys(k)
print(dic2)

#insert value to a existing key
dic2["a"]="b"
print(dic2)

 

2) printing all keys 

#find all the keys
k=dic2.keys()

#find all the keys and save them in a list
k_list=[]
for i in k:
  k_list.append(i)

print(k_list)

 

3) inserting and printing all values

#insert values
values=[1,2,3]
for i in range(len(k_list)):
  dic2[k_list[i]]=values[i]

print(dic2)

#find values
v=dic2.values()

#find all the keys and save them in a list
v_list=[]
for i in v:
  v_list.append(i)

print(v_list)

 

4) removing key-value pairs 

#deleting key-value pair
del dic2['a']
print(dic2)

'Data Science' 카테고리의 다른 글

Kaggle : Data science sample / examples for data analysis / real-world data  (0) 2021.08.08
[Python] List  (0) 2021.08.08

댓글