Python-a05-Dictionaries

This article shows the examples of Dictionaries in python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
## basic
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student) # {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student['name']) # John
print(student['courses'][0]) # Math
print(student['phone']) # error

print(student.get('name')) # John
print(student.get('phone')) # None
print(student.get('phone', 'Not Found')) # Not Found

# add and update element
student['phone'] = '555'
student['name'] = 'Bob'
print(student) # {'name': 'Bob', 'phone': '555', 'age': 25, 'courses': ['Math', 'CompSci']}

student.update({'name': 'Jane', 'age': 26, 'phone': '666'})
print(student) # {'name': 'Jane', 'phone': '666', 'age': 26, 'courses': ['Math', 'CompSci']}

# delete element
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
del student['age']
print(student) # {'name': 'John', 'courses': ['Math', 'CompSci']}

age = student.pop('age')
print(student) # {'name': 'John', 'courses': ['Math', 'CompSci']}
print(age) # 25

# loop
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student.keys()) # dict_keys(['name', 'age', 'courses'])
print(student.values()) # dict_values(['John', 25, ['Math', 'CompSci']])
print(student.items()) # dict_items([('name':'John'), ('age':25), ('courses':['Math', 'CompSci'])])

for key in student:
print(key) # name; age; courses

for key,value in student.items():
print(key,value) #name John; age 25; courses ['Math', 'CompSci']