Python Dictionaries

python dictonaries

Python Dictionaries are another data storage container similar to lists and tuples with one key difference.  Dictionaries store key: value pairs.  

Similar to lists, dictionaries are mutable and can contain mixed content including tuples (assuming the values are all of the same types), lists, strings, integers, etc.  

The point of the key: value pair model is that every key stored within the dictionary is unique.  In effect, the dictionary is designed to store the values of a list of unique items or properties.   

Following things are true in Dictionaries 

1.      When adding to or creating a dictionary, all entries must be in a key:value pair format.  If either the key or the value is missing an exception will be given. 

2.     If a key:value pair is added to a dictionary and the key already exists in the dictionary, the old key and value will be discarded for the new entry.

 3.     Values can be updated only when a key is provided.

 4.     key:value pairs are always deleted together – there is no way to delete just the value or just the key.

5. Lists cannot be used as keys.

Here are some common operations on dictionaries. 

Create an empty dictionary in python:

>>> x={} 

Create a dictionary in python:

 >>> x=dict(name='john', age=35, height=6) 
 >>> print(x)

Output

{'name': 'john', 'age': 35, 'height': 6} 

Test if a key exists:

 >>> if 'age' in x.keys():      
          print('found it!') 

Output

found it! 

Get a value for a key:

>>> y=x['height']
 >>> print('Height = ' + str(y))

Output

Height = 6

Python Dictionaries List all keys:

>>> for y in x.keys():     
           print(y)

Output

 Name
 age 
height 

Print keys and values:

>>> for y in x.keys(): 

    v=x[y] 
    if type(v)!='str': 
     v=str(v) 
    print(y + '=' + v)

Output

name=john 
age=35 
height=6 

Python Dictionaries Update a value for a key:

>>> x['age']=40 
>>> print(x) 

Output

{'name': 'john', 'age': 40, 'height': 6}

Python Dictionaries Delete a key: value pair

>>> del(x['height']) 
>>> print(x) 
 

Output

{'name': 'john', 'age': 40}

Python Dictionaries Add a Key: Value pair

>>> x['height']=6
 >>> print(x) 

Output

{'name': 'john', 'age': 40, 'height': 6}

Dumping all keys or values into a list:

 >>> list(x.keys()) # keys as a list 
 ['name', 'age', 'height']

Output


 >>> list(x.values())  # values as a list ['john', 40, 6]