Python Dictionary
Python Dictionary
Removes the key-value pair and returns the value of the key.
marks = student.pop("marks")
print(marks) # 92
print(student) # {'name': 'Aman'}
Removes and returns the last inserted key-value pair (since Python 3.7+).
student.clear()
print(student) # {}
Returns value of
key; returns
d.get(key[, default]) student.get("age", 0)
default if key
not found
Adds key-value
pairs from
d.update(other_dict) student.update({"school":"ABC"})
another
dictionary
Removes and
d.pop(key[, default]) returns the value student.pop("class")
of the key
d.clear() student.clear()
Removes all
Function / Method Description Example
items
Returns a shallow
d.copy() new_dict = student.copy()
copy
Dictionary Traversal
Emp={'name':'ram','sal':20000,'age':23}
for x in d:
print(x,’:’,d[x])
Emp={'name':'ram','sal':20000,'age':23}
for x in Emp.items():
print(x)
for x in Emp.values():
print(x)
Output:
name:ram
sal:20000
age:23
('name', 'ram')
('sal', 20000)
('age', 23)
name ram
sal 20000
age 23
ram
20000
23
Dictionary Examples
# Creating a dictionary
student = {"name": "Aman", "class": 12, "marks": 92}
# Adding a key
student["age"] = 17
# Updating a value
student["marks"] = 95
del d["b"]
print(d)
x = d.pop("marks")
print(x)
print(d)
d = {"x": 100}
del d["y"]
b) Returns None
c) Error
removed_item = _______________
print(removed_item)
print(d.get("c", 0))
print(d["b"])
d[3] = "three"
d[2] = "TWO"
print(d)
print(d.popitem())
print(d)
Section E: Programming Questions
Q2. Write a Python function that accepts a dictionary and returns the
key with the maximum value.
employees = {