Data

Map

Python

 

Defining Dictionary

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

Dictionary is a collection of key-value pairs.

Dictionary in Python is similar to HashMaps in Java.

 

Getting Key

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

val = dict1['name']   # Sam

You can access a value in a dictionary using the bracket operator.

 

Getting Key/Value

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

dict1['age'] = 21

You can set a key or update an existing key with a new value using the bracket operator.

Here we are setting a value for key age to 21.

 

Length

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

length = len(dict1);  # 2

The len() function returns the number of elements in a Dictionary.

 

Deleting Key

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

del dict1['age']    # dict1 -> {'name': 'Sam'}
dict1.pop('name')   # dict1 -> {}

There are a couple of ways to remove a key from Dictionaries:

  • del keyword
  • pop() method
 

Listing Keys

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

keys = list(dict1.keys())

The keys() function returns keys inside a dictionary.

There is a difference between return types of keys() method in Python2 and Python3. You can use list() function to always get a List type.

 

Listing Values

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

values = list(dict1.values())

The values() function returns values inside a dictionary.

There is a difference between return types of values() method in Python2 and Python3. You can use list() function to always get a List type.