Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Dictionaries

Goal
• Learn about dictionaries (dict) in Python
• Store key-value pairs
my_dict = {
'Key 1': 'Value 1',
'Key 2': 'Value 2'
}

my_dict['Key 1']

'Value 1'

my_dict['Key 2']

'Value 2'

my_dict['Key 3'] = 'Value 3'

my_dict

{'Key 1': 'Value 1', 'Key 2': 'Value 2', 'Key 3': 'Value 3'}

my_dict['Key 2'] = 'Value 3'

my_dict

{'Key 1': 'Value 1', 'Key 2': 'Value 3', 'Key 3': 'Value 3'}

car = {
'Brand': "Lamborghini",
'Model': "Sián",
'Year': 2020
}

car

{'Brand': 'Lamborghini', 'Model': 'Sián', 'Year': 2020}

items = ['Pen', 'Scissor', 'Pen', 'Pen', 'Scissor']

count = {}
for item in items:
count[item] = count.get(item, 0) + 1

count

{'Pen': 3, 'Scissor': 2}
for key, value in count.items():
print(key, value)

Pen 3
Scissor 2

for key, value in car.items():


print(key, value)

Brand Lamborghini
Model Sián
Year 2020

car.keys()

dict_keys(['Brand', 'Model', 'Year'])

list(car.keys())

['Brand', 'Model', 'Year']

type(list(car.keys()))

list

list(count.keys())

['Pen', 'Scissor']

You might also like