Net-informations.com
SiteMap  | About    

Python Dictionary

A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Dictionaries, in Python, are also known as "mappings", because they "map" or "associate" key objects to value objects. Dictionaries are indexed by keys and they can be seen as associative arrays. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

The Python dictionaries are very optimized hash-tables. It is an array whose indexes are obtained using a hash function on the keys. It can provide a very efficient way to search for items in large amounts of data, particularly data that is not otherwise easily searchable. A pair of braces creates an empty dictionary: {}.

How to create an Excel Document Programmatically

Creating an Empty Dictionary

example

output

How to create a dictionary?

The contents of a dict can be written as a series of key:value pairs within braces { }

example

output

Accessing Values from Dictionary

example

output

Remove values from Dictionaries

You can remove an entry from Dictionaries using the key.

example

output

The clear() method of Dictionary remove all entries in dictionary

example

output

If you want to delete entire dictionary, you can use "del" command.

example

output

The error message showing in the above case because the Dictionary does not exist.

Updating Dictionary contents

example

output

Retrieve whole Dictionary entries

We can use loop through whole entries in a Dictionary. When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

example

output

Retrieve Keys and Values in a List

example

output

Arbitrary key and value

Python Dictionary comprehensions can be used to create dictionaries from arbitrary key and value expressions.

example

output

Copying a Dictionary

A dictionary can be copied with the method copy()

example

output

Merging Dictionaries

The update() method of Dictionary is to merges the keys and values of one dictionary into another, overwriting values of the same key.

example

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.