Python Tutorial for Beginners - 4. Dictionaries - Working with Key-Value Pairs

Table of Contents

  1. Run Code 1 in Python
  2. Run Code 2 in Python
  3. Run Code 3 in Python
  4. Run Code 4 in Python
  5. Run Code 5 in Python
  6. Run Code 6 in Python
  7. Run Code 7 in Python
  8. Run Code 8 in Python
  9. Run Code 9 in Python

Run Code 1 in Python

1
2
3
4
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

for key, value in student.items():
    print(key, value) 

start.py

Run Code 2 in Python

1
2
3
4
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

print(student)
print(student['courses'])

start.py

Run Code 3 in Python

1
2
3
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

print(student['phone']) #KeyError: 'phone'

start.py

Run Code 4 in Python

1
2
3
4
5
6
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

print(student.get('name'))
print(student.get('phone'))

print(student.get('phone', 'Not found'))

start.py

Run Code 5 in Python

1
2
3
4
5
6
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

student['phone'] = '555-5555'
student['name'] = 'MT'

print(student)

start.py

Run Code 6 in Python

1
2
3
4
5
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

student.update({'name': 'MT', 'age': 31, 'phone':'0401234567'})

print(student)

start.py

Run Code 7 in Python

1
2
3
4
5
6
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

age = student.pop('age')

print(student)
print(age)

start.py

Run Code 8 in Python

1
2
3
4
5
6
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}


print(len(student))
print(student.values())
print(student.items())

start.py

Run Code 9 in Python

1
2
3
4
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

for key, value in student.items():
    print(key, value) 

start.py