Dictionary Functions and Methods

45 min read Dictionaries and Python Modules

This is a free course. Log in to run the code exercises and track your progress.

Dictionary Functions and Methods

  • len(d): number of pairs. dict(): make a dictionary, e.g. dict(a=1, b=2) or dict([("a", 1)]).
  • keys(), values(), items(): views of the keys, the values, and the (key, value) pairs.
  • get(k, default): the value, or the default if the key is missing.
  • update(other): add or overwrite the pairs of another dictionary.
  • pop(k): remove a key and return its value; popitem(): remove and return the last inserted pair; clear(): empty the dictionary; del d[k]: delete one pair.
  • fromkeys(keys, value): a new dictionary with the given keys; copy(): a shallow copy; setdefault(k, v): the value of k, inserting v first if it is missing.
  • min(), max(), sorted() work on the keys.
salary = {"Anil": 52000, "Bina": 61000, "Chetan": 45000}
for name, pay in salary.items():
    if pay > 50000:
        print(name)               # Anil, Bina
print(max(salary, key=salary.get))  # Bina: the key with the largest value
salary.update({"Chetan": 48000, "Dev": 39000})
print(sorted(salary))               # ['Anil', 'Bina', 'Chetan', 'Dev']
Python exercise

Read n, then n lines of name salary. Store them in a dictionary and print the names of employees earning more than 50000, in input order, one per line, then a final line Total: with the sum of all salaries.

n = int(input())
salary = {}
for _ in range(n):
    name, pay = input().split()
    salary[name] = int(pay)
# print the names with salary above 50000
print("Total:", 0)

Log in to edit and run this code.