Dictionary in python.

Dictionary ({})


Python provide dictionary structure to deal with key and value as pair. It is a container which contains data in pair of '{ }'. The pair key and value is known as Item. The key and value must be separated by ':' and each pair of item is separated by ' , '.

Different item s are enclosed within '{ }' and this create dictionary

Example:

D={101:'AAA',102:'BBB',103:'CCC'} print(D)

output:

{101:'AAA',102:'BBB',103:'CCC'}

The value in the dictionary are mutable i.e it can be change however the key is immutable and must be unique for every item. The key is used to access the specific value. The values can be updated but the key can not be changed. The dictinary is also known as Associated Array.

Example:

Create a program for dictionary and print any two value using its key and update a value using key and print again. a={name:'Harsh', class:'SYIT' , div:'A'}

output:

{name:'Harsh', class:'SYIT' , div:'A'}

The values in dictionary can be any datatype but the keys must be of immutable datatype (string , number or tuple).

Example: Empty dictionary {}

Methods in Dictionary:

Copy()

Copy() method is used to copy the entire dictionary to move to new dictionary.

dict={102:'Harsh', 202:'Manish'} dict2=dict.copy() print(dict2) output: {102:'Harsh', 202:'Manish}

Update()

Update() method is to update a dictionary by adding a new entry to a key value pair to an existing entry or by deleting an existing entry.

dict={102:'Harsh', 202:'Manish'} dict.update({303:'Suraj'}) print(dict) output: {102:'Harsh', 202:'Manish ,303:'Suraj'}

item()

Item() method return a list of tuples pair (keys, values) in the dictionary

dict={102:'Harsh', 202:'Manish'} print(dict.items()) output: dict_items([(102, 'Harsh'), (202, 'Manish')])

len()

len() method gives the number of pair in the dictionary.

dict={102:'Harsh', 202:'Manish'} print(len(dict)) output: 2

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.