DICTIONARY Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON is an unordered collection of data values, which is used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, a Dictionary consists of key-value pair. Key-value is provided within the dictionary to form it more optimized. In the representation of a dictionary data type, each key-value pair during a Dictionary is separated by a colon: whereas each key’s separated by a ‘comma’.

If we want to represent a group of values as key-value pairs then we should go for dict data type.

Eg: d = {101:’Cloud’,102:’And’,103:’Clear’}

Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value.

dict is mutable and the order won’t be preserved.

  • Duplicate keys are not allowed but values can be duplicated.
  • Hetrogeneous objects are allowed for both key and values.
  • Insertion order is not preserved
  • Dictionaries are mutable
  • Dictionaries are dynamic
  • indexing and slicing concepts are not applicable

How to Create Dictionary?

d = {} OR d = dict()

We are creating empty dictionary. We can add entries as follows

1) d[100]=”Shibha”

2) d[200]=”ravi”

3) d[300]=”shiva”

4) print(d) à {100: ‘Shibha’, 200: ‘ravi’, 300: ‘shiva’}

If we know data in advance, then we can create dictionary as follows

 

d = {100:’Shibha’ ,200:’ravi’, 300:’shiva’}

d = {key:value, key:value}

How to Access Data from the Dictionary?

We can access data by using keys.

d = {100:’Shibha’ ,200:’ravi’, 300:’shiva’}

print(d[100]) ## Shibha

print(d[200],d[300]) ### ‘ravi’, ‘shiva’

print(d[400]) à KeyError: 400

If the specified key is not available then we will get KeyError. We can prevent this by checking whether key is already available or not by using has_key() function or by using in operator.

d.has_key(400) à Returns 1 if key is available otherwise returns 0

But has_key() function is available only in Python 2 but not in Python 3. Hence compulsory we have to use in operator.

 

Important Functions of Dictionary:

1) dict():

To create a dictionary

d = dict() à It creates empty dictionary

d = dict({100:”durga”,200:”ravi”}) à It creates dictionary with specified elements

d = dict([(100,”durga”),(200,”shiva”),(300,”ravi”)])

 

It creates dictionary with the given list of tuple elements

2) len()

Returns the number of items in the dictionary.

3) clear():

To remove all elements from the dictionary.

 

4) get():

To get the value associated with the key

d.get(key) à  If the key is available then returns the corresponding value otherwise returns None.It wont raise any error.

d.get(key,defaultvalue)  à If the key is available then returns the corresponding value otherwise returns default value.

 

5) pop():

d.pop(key)

It removes the entry associated with the specified key and returns the corresponding value.

If the specified key is not available then we will get KeyError.

1) d={100:”ravi”,300:”shiva”}

2) print(d.pop(100))

3) print(d)

4) print(d.pop(400))

 

Output

Ravi

{300: ‘shiva’}

KeyError: 400

 

6) keys():

It returns all keys associated eith dictionary.

1) d={100:”durga”,200:”ravi”,300:”shiva”}

2) print(d.keys())

3) for k in d.keys():

4) print(k)

Output

dict_keys([100, 200, 300])

100

200

300

 

7) values():

It returns all values associated with the dictionary.

1) d={100:”divya”,200:”Shubha”,300:”pooja”}

2) print(d.values())

3) for v in d.values():

4) print(v)

 

Output

dict_values([‘divya’, ‘shubha’, ‘pooja’])

divya

shubha

pooja

 

 

8) items():

It returns list of tuples representing key-value pairs.

[(k,v),(k,v),(k,v)]

1) d={100:”divya”,200:”shubha”,300:”pooja”}

2) for k,v in d.items():

3) print(k,”–“,v)

 

Output

100 — divya

200 — shubha

300 — pooja

 

9) copy():

To create exactly duplicate dictionary (cloned copy)

d1 = d.copy();

10) setdefault():

d.setdefault(k,v)  à If the key is already available then this function returns the corresponding value.

If the key is not available then the specified key-value will be added as new item to the dictionary.

11) update():

d.update(x)

All items present in the dictionary x will be added to dictionary d

This is all about DICTIONARY Data Structure in PYTHON and Dictionary functions like dict, len, clear, get, pop, keys, values, items, copy, setdefault & update.

 

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

Python Exception Handling Using try, except and finally statement

File Handling in Python

Python Random module

Python reduce() Function

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers