Python - Dictionary Basic Operations

Introduction

You create dictionaries with literals and store and access items by key with indexing:

Demo

D = {'test': 2, 'ham': 1, 'eggs': 3}      # Make a dictionary 
print( D['test'] )                                 # Fetch a value by key 
print( D )                                         # Order is "scrambled"
#  w  ww.ja  v a 2  s .c om

Result

Here, the dictionary is assigned to the variable D.

The value of the key 'test' is the integer 2, and so on.

The built-in len function it returns the number of items stored in the dictionary.

The dictionary in membership operator allows you to test for key existence.

The keys method returns all the keys in the dictionary.

The keys list can be sorted:

Demo

D = {'test': 2, 'ham': 1, 'eggs': 3}      # Make a dictionary 
# from  w  ww  . ja v a 2 s . c om
print( len(D) )                           # Number of entries in dictionary 
print( 'ham' in D )                       # Key membership test alternative 
print( list(D.keys()) )                   # Create a new list of D's keys

Result