Dot11 Guru

Python, scripting

Python 101 – Dictionaries

A dictionary is a group of values that have associated keys. A dictionary in python is encapsulated within curly {} brackets. The key is seperated from the value using a colon : and entire key + values are seperated using a comma. An empty dictionary only has the curly brackets

empty = {}
dict1 = {"Name": "Ben", "Location": "Earth", "Timezone": "CET"}

To call find the value associated to a specific key, you can do the following

print(dict1['Name'])
Ben

You can add or update the dictionary by performing

dict1['Location'] = "unknown"
dict1['Mood'] = "Happy"
print(dict1['Location'])
unknown
print(dict1['Mood'])
Happy

There are a few options to consider when wanting to delete items from a dictionary.

del dict1['Name'] # remove entry with key 'Name'
dict1.clear()     # remove all entries in dict
del dict1         # delete entire dictionary

Share this:

Leave a Reply