Dictionary In Python Tutorial – POFTUT

Dictionary In Python Tutorial

Dictionaries are complex data structures that hold information about the different types and related information. Dictionaries also called associative memories or associative arrays in different languages. Dictionaries generally format in key and value pair. Keys are used to label and search and find values.

Create Dictionary

As we say before we will provide key and value pairs. In this example, we will create a phone book. The name of the phonebook is pb and have some names and phone numbers.

pb = { 'ismail':4090, 'ahmet':4091}

We have two records with keys ismail and ahmet their phone numbers are 4090 and 4091 . The phone numbers type is an integer. We can also define different types. We associate keys and values with : .

Get Value with Key

Getting values by providing keys. In this example, we provide the key ismail and get the value 4090 in the following lines. As we guess the return type will be integer too.

ismail = pb['ismail']

Add Key Value to Dictionary

Adding new keys and values is as easy as getting them. We will just provide the key name and the related value by using an equal sign like below. We will add key ali and related phone number 4092 into the phone book in the following example.

pb['ali'] = 4092

Remove Key Value From Dictionary

We can remove the given key and value by using the del keyword. del is a keyword in a python programming language which is used related to remove and delete operations like dictionaries, list, etc enumerable types. In the following example, we will delete the key ali and its related value 4093 by using del function.


Using Index As Key

Dictionaries provide another way for keying all ready existing key-value pairs. We can use index numbers as keys. For example, the first key value in the pb is ismail:4090 if we provide index number 0 we can get the same value from the dictionary as below. But before we should convert dictionary values into a list.

>>> list(pb.values())[0] 

LEARN MORE  Bash Printf Function Tutorial with Examples

Leave a Comment