Dictionaries

phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)

# {'John': 938477566, 'Jill': 947662781, 'Jack': 938377264}

phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
print(phonebook)

# {'John': 938477566, 'Jill': 947662781, 'Jack': 938377264}

Iterating over dictionaries

Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:

phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))

# Phone number of John is 938477566
# Phone number of Jill is 947662781
# Phone number of Jack is 938377264

Removing a value

iter()

Last updated

Was this helpful?