Dictionary

This dictionary is a collection of key-value pairs. Keys are used to identify the values; each key must be unique. Values can be any object, including numbers, strings, lists, and other dictionaries. Dictionaries are created using curly braces ({}). To add a key-value pair to a dictionary, you use the colon (:). For example, the following code creates a dictionary with key-value pairs:

Python
# create dictionary
dictContact = {
    "Jan": "554-3432",
    "mike": "534-2332",
    "sarah": "154-3233",
    }

print(dictContact) 
# output {'Jan': 554-3432, 'mike': 534-2332, 'sarah': 154-3233}

print(dictContact.keys()) 
# output dict_keys(['name', 'year', 'rating', 'actors'])
print(dictContact.values())  

# add new key value pair
dictContact["john"] = "123-4567"
print(dictContact) 
# output {'Jan': 554-3432, 'mike': 534-2332, 'sarah': 154-3233, 'john': 123-4567}

# delete key value pair
del dictContact["john"]
print(dictContact) 
# output {'Jan': 554-3432, 'mike': 534-2332, 'sarah': 154-3233}

# update key value pair
dictContact["Jan"] = "123-4567" # update Jan's phone number
print(dictContact) 
# output {'Jan': 123-4567, 'mike': 534-2332, 'sarah': 154-3233}

# get value of a key
print(dictContact["Jan"]) # output 123-4567

Close Bitnami banner
Bitnami