Loading...

Python tutorial

Dictionaries

A dictionary is a set of items ;each item consists of key and a value. You define a dictionary using braces:

capitals ={
     'India' : 'Delhi',
     'Arunachal Pradesh' : 'Itanagar',
     'Assam' : 'Dispur',
          }




You  access the value associated with a key by stating the dictionary name, followed by the key in brackets:

print(capitals['India'])
output:'Delhi'

Add items to an existing dictionary by placing the new key in brackets and providing the value:

capitals['Bihar']='Patna'

Remove iteams from a dictionary using the del Keyword:

del capitals['India']

This removes both the key and its associated value from the dictionary.

Dictionary Methods

The get() method returns the value associated with a key if that key exists in dictionary.If the key does'nt exist, get() returns None,not  an error.

You can also pass a dewfault value to to be returnesd if the key doesn't exist 

print(capitals.get('India')
output:'Delhi'
print(capitals.get('Manipur'))
output:''
print(capitals.get('Manipur','Imphal'))
output:'Imphal'

The methods keys(),values(),and iteams() return different aspects of a dictionary that also help you loop through the dictionary:

print(capitals.keys())
output:dict_keys(['India','Arunachal Pradesh','Assam']
print(capitals.values())
output:dict_values(['Delhi','Itanagar','Dispur']
print(capitals.iteams())
output:dict_items([('India','Delhi'),('Arunachal Pradesh','Itanagar'),('Assam','Dispur')])

Choose one of these methods based on what you're doing with each item.

Looping Through A Dictionary

Loop through a dictionary to access just the keys.This is the default behaviour when loooping through a dictionary 

for state in capitals:
    print(f"state :{state}")
output: state: India
        state: Arunachal Pradesh
        state: Assam

You can also access just the values in a dicitionary:

for capital in capitals.values():
      print(f"Capital:{capital}")
output: Capital: Delhi
        Capital: Itanagar
        Capital: Dispur

To work with  both keys and values, use the items() method:

for state,capitalin capitals.items():
print(f"{capital},{state}")
output: Delhi,India
        Itanagar,Arunachal Pradesh
        Dispur,Assam

Example Dictionaries

One use of a dictionary is to represent a collection of key-value pairs with a consistent structure ,such as aglossary: