Python Dictionary – Data Structure

python-dictionary-feature-image

In this tutorial, we’re gonna look at Python Dictionary data type: what it is, how to create, add, access, remove item and Python built-in methods.

Related Post: Python List functions

Python Dictionary data type

Python Dictionary is a collection of items. Unlike List, Dictionary doesn’t have indexes but keys. A key with its associated value is called a key-value pair.

Dictionary is covered by braces ({}):

Create a Python Dictionary

Usual way

We can use integer values as keys, just like List for indexes, but they do not have to start at 0 and can be any number:

Dictionary can be created with mixed keys:

Use dict() contructor

We can also create a Dictionary with dict() built-in function:

If the keys are simple strings:

Use Python Dictionary Comprehension

Access items from Python Dictionary

Usual way

Use key inside square brackets:

Use get() method

We can use get() method that returns None instead of KeyError when the key is not found:

Access all keys/values – Iterate a Python Dictionary

Add item to Python Dictionary

– The simplest way is using a new key and assign a value:

– Or we can use update() method:

Update an item of Python Dictionary

Similar to add an item, but instead of using a new key, we update with the old key:

Remove an item from Python Dictionary

Pop item by key

pop() method to remove item by its key:

Pop arbitrary item

popitem() method to remove arbitrary item:

*Note: From version 3.7: LIFO order. In prior versions, popitem() for arbitrary item.

Remove all items

We can keep the dictionary and remove all items with clear() method:

Use del statement

del statement to remove specific item (by key):

– delete the dictionary completely (this is different from clear() method):

Check if a key/value exists in Python Dictionary

We can know whether a key/value is or is not in Dictionary using in and not in operators:

Set default value for a key in Python Dictionary

Sometimes we want to set default value for a key that doesn’t already have a value. It’s something like this:

setdefault() method can make this happen in just one line of code:

Python Dictionary built-in functions

all(): returns True if all keys are true, or if dictionary is empty.
any(): returns True if any key is true, returns False if dictionary is empty.
len(): returns number of items in dictionary.
sorted(): returns a new sorted list of keys in the dictionary.



By grokonez | December 24, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*