Dictionary In Python Tutorial With Examples

Dictionaries is complex data structures those hold information about different type 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 pair. 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 . Phone numbers type is 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 are  easy as getting them. We will just provide the key name and the related value by using 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 python programming language which is used related remove and delete operation 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 provides 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  we can get the same value from the dictionary like below. But before we should convert dictionary values into list.

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

LEARN MORE  Python For Loop Tutorial With Examples and Range/Xrange Functions

Leave a Comment