Tuesday, 28 May 2019

dictionary data type

dict:(Dictionary Data type)

It is a collection of elements in the form of key and value pairs.
If you want to represent a group of values as key-value pairs then we go for dict data types.

The dict represents the key and the next one becomes its value.
The key and its value should be separated by a colon (:) and every pair should be separated by comma. All the elements should be enclosed inside braces (curly brackets).
We can create dict by typing the roll numbers and names of students. Dict data type is mutable.


Syntax:
Variable={key1:’value’, key2:’value’,..}

Example:
(1. )a={10:’ram’,20:’sita’,30:’rajesh’}
print(a)
{10: 'ram', 20: 'sita', 30: 'rajesh'}

Other Examples:

(2.) >>> a[10]='rajendra' #We can modify the values
>>> print(a)
{10: 'rajendra', 20: 'sita', 30: 'rajesh'}
(3)>>> b={'a':'apple','c':'cat'}
>>> b['b']='bat' #we can add the values
>>> print(b)
{'a': 'apple', 'c': 'cat', 'b': 'bat'}

(4) Different data types also we can use in dict
>>> s={10:"raj",10+3j:True,2.4:3.6}

(5)  a={} # empty dict can be created, later we can add

a[2]=”ram”
a[4]=’sita’
print(a)

Empty dict can be created:
>>> a={} # empty dictionary
>>> type(a)
<class 'dict'>
>>> a[4]='ravi' #we can add the key values
>>> a[7]='sita'
>>> print(a)
{4: 'ravi', 7: 'sita'}

Values can be duplicated. Duplicate values can be given.

>>> a={10:'rajendra',20:'rajendra',30:"siva"}
>>> print(a)
{10: 'rajendra', 20: 'rajendra', 30: 'siva'}

Duplicated key values are not allowed
>>> b={10:'ravi',10:'siva'}
>>> print(b)
{10: 'siva'}

Dictionary is a mutable
>>> b={10:'ravi',10:'siva'}
b[10]=’rajendra’ #we can modify the values
>>>print(b)
b={10:' rajendra',10:'siva'}

dictionary of strings
>>> a={"hi":10,"vij":30,"hyd":40}
>>> print(a)
{'hi': 10, 'vij': 30, 'hyd': 40}
>>> a["hi"] #accessing the values
10
>>> 

To access only values
>>> a={10:"ravi",20:"siva"}
>>> print(a.values())

To access only keys in the dictionary
dict_values(['ravi', 'siva'])
>>> print(a.keys())
dict_keys([10, 20])
>>> 

Keys are not modifiable if you try to modify, it will be added
Ex:
>>> a={10:'ravi',20:'siva'}
>>> a['ravi']=30
>>> print(a)
{10: 'ravi', 20: 'siva', 'ravi': 30}

>>> 
5. #deleting  dict values
s={10:'rj',20:"sita"}
>>> del s[10]

6. To delete entire dict we can use 
>>> s={10:'rj',20:"sita"}
>>> del s # it deletes entire dictionary elements

7. To delete a particular element from the dictionary we can use

>>> s={10:'rj',20:"sita"}
>>> s.pop(20) 

8. To delete a random element from the dictionary we can use (it mostly removes end of the elements)
       >>> s={10:'raj',20:"sita",30:"Ravi",40:"krish",16:"ram"}
       >>> s.popitem()
       (16, 'ram')
       >>> s.popitem()
       (40, 'krish')
       >>> s.popitem()
       (30, 'Ravi')
       >>>       
9. To delete all the elements from the dictonary:
 >>> s={10:'raj',20:"sita",30:"Ravi",40:"krish",16:"ram"}
 >>>s.clear()

10. Nested dictionary

>>>a = {1: 'Rama', 2: 'Sita', 3:{'V' : 'Vij', 'H' : 'Hyd', 'R' : 'Rama'}}
>>>print(a)

"""output
{1: 'Rama', 2: 'Sita', 3: {'V': 'Vij', 'H': 'Hyd', 'R': 'Rama'}}
>>> """


update() :
update method is used to append a new element to it

>>>a = {"1" : "C", "2" : "Java"}
>>>print(a)
>>>a["3"] = "C++" #Adding the key-value
>>>a.update({"4" : "JavaScript"})#Another way to adding the key-value
>>>print(a)#displaying the all the dict key-values

"""
output:

{'1': 'C', '2': 'Java'}
{'1': 'C', '2': 'Java', '3': 'C++', '4': 'JavaScript'}

"""

Assignments:

1. Which of the following statements create a dictionary? 
a) d = {}
b) d = {“Ram”:10, “Ravi”:35}
c) d = {10:”Krishna”, 35:”Radha”}
d) All of the mentioned
Answer: d (Dictionaries are created by specifying keys and values. )

2. Read the code shown below carefully and pick out the keys? 
d = {"Rama":10, "Krishna":35}
a) “Rama”, 10, 35, and “Krishna”
b) “Rama” and “Krishna”
c) 10 and 35
d) d = (10:”Rama”,345:”Krishna”)
Answer: b (Dictionaries appear in the form of keys and values. )

3. d = {"Rama":10, "Krishna":35}, to delete the entry for “Rama” what command do we use 
a) d.delete(“Rama”:10)
b) d.delete(“Rama”)
c) del d[“Rama”].
d) del d(“Rama”:10)

Answer: c

YouTube related videos

Next topic: Mixed dictionary data type
bytes data type
Previous topic: range data type

You may like the following posts:
  Built-in Data types

1 comment:

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...