Python Dictionary

Chapter 5 • Python
Chapter 5 • Python

Sequence Data Type : Dictionary

The ultimate key-value store mapping in Python. Powerful, lightning-fast, and mutable mapping database structures optimized for rapid retrieval!

Key-Value Pairs
Fast Lookup
Mutable Data
Nestable

Introduction :

  • बड़ी मात्रा में डेटा स्टोर करने के लिए इसका उपयोग होता है।
  • यह data ‘key : value’ pair के रूप में होता है जहाँ पर key (immutable) होती है तथा value (mutable) होती है।
  • Key तथा Value को (:) से Separate (अलग) किया जाता है।
  • dictionary के data को , से अलग किया जाता है तथा comma यह curly bracket के अंदर लिखी जाती है।
📝 NOTE → Key : Value की एक unique id होती है।
python
{} → Empty dictionary
{1:'aaa', 2:'bbb', 3:'ccc'} → Dictionary of names

Creating a Dictionary

डिक्शनरी बनाने के दो तरीके हैं –

  1. By assigning values
  2. Dynamically via keyboard

1. By assigning Value :

Dictionary बनाने के लिए key:value pair को { } में लिखा जाता है और उसे एक नाम में assign कर दिया जाता है।

Syntax :

python
<dictionary name> = { <key>:<value>, <key>:<value> }

Example :

python
players = {1:'Sachin', 2:'Dhoni', 3:'Rohit'}

2. Dynamically via Keyboard :

Input Function का प्रयोग करके dynamic dictionary बनाई जाती है।

Syntax :

python
<key variable> = input("any message")
<value variable> = input("any message")

Example :

python
k = input("Enter dict key")
v = input("Enter value")
dict[k] = v

Program :

एक प्रोग्राम लिखें जिसमें 3 शहरों का तापमान इनपुट करके उनका उपयोग कर एक डिक्शनरी बनाएं। शहर का नाम key और तापमान को value के रूप में लें।

python
dict = {}
for a in range(3):
    k = input("Enter city name")
    v = input("Enter temp of city")
    dict[k] = v
print(dict)

Accessing the Dictionary

दो प्रकार से dictionary access की जाती है –

1. Accessing whole dictionary :

पूरी डिक्शनरी को एक साथ access करने के लिए इसके नाम का प्रयोग किया जाता है।

Example :

python
marks = {1:38, 2:41, 3:29}
print(marks)
💡 NOTE : * के साथ डिक्शनरी प्रिंट करते समय बिना punctuation marks के डिक्शनरी की key प्रिंट होती है।

2. Accessing individual element :

डिक्शनरी में data key:value pair के रूप में स्टोर होता है। key का प्रयोग करके उसकी value को access किया जाता है।

Syntax :

python
<dictionary name>[<key>]

Example :

python
marks = {1:38, 2:41, 3:29}
print(marks[2])

Program :

पाँच छात्रों के अंकों की डिक्शनरी बनाने हेतु एक प्रोग्राम लिखें और डिक्शनरी को प्रिंट करें। किसी एक छात्र के अंक की print करने के लिए यूजर से उसका रोल नंबर इनपुट लेकर अंक प्रिंट करें।

python
marks = {1:39, 2:46, 3:30, 4:37, 5:42}
print(marks)

while(True):
    print("Roll numbers is :", marks)
    k = input("Enter roll no.")
    print("Marks of roll no.", k, "is", marks[k])

Traversing the Dictionary

डिक्शनरी के element access करने के लिए for loop में dictionary के नाम का प्रयोग किया जाता है। यह process traversing है।

Syntax :

python
for <control variable> in <dictionary name>:
    body of loop

Example :

python
marks = {1:39, 2:46, 3:30, 4:37, 5:42}
for a in marks:
    print(marks[a])

Dictionary Operations :

1. Adding element to dictionary :

Assignment method का प्रयोग करके डिक्शनरी में element जोड़े जाते हैं।

Syntax :

python
<dictionary name>[<key>] = <value>

Example :

python
Cricket = {1:'Virat', 2:'Dhoni'}
Cricket[3] = 'Sachin'
print(Cricket)

2. Creating dictionary using key & value separately :

zip function तथा dict function का प्रयोग करके key तथा value को separately input के द्वारा dictionary बनाई जाती है।

Syntax :

python
<dictionary name> = dict(zip([<list of keys>], [<list of values>]))

Example :

python
Cricket = dict(zip((1,2,3), ('Sachin','Dhoni','Virat')))
print(Cricket)

3. Creating dictionary using key:value pairs as list :

इस method में key और value की list को dict function में argument pass किया जाता है।

Syntax :

python
<dictionary name> = dict([[<key,value pair>], [<key,value pair>]])

Example :

python
Cricket = dict([[1,"Sachin"], [2,"Rohit"], [3,"Dhoni"]])
print(Cricket)

Program :

क्रिकेटर के नाम से एक डिक्शनरी बनाने के लिए एक प्रोग्राम लिखें जिसमें क्रिकेटर के नाम के रूप में value और उनके index के रूप में key का उपयोग करें। एलिमेंट्स की संख्या यूजर पर निर्भर होनी चाहिए।

python
c = 1
Cricket = {}
ch = 1

while(ch == 1):
    v = input("Enter player name")
    Cricket[c] = v
    c = c + 1
    ch = input("Do you want to add any more data yes=1 and no=0")

print(Cricket)

4. Updating dictionary element :

डिक्शनरी में पहले से उपस्थित key का प्रयोग करके element update किया जा सकता है। यह नए element जोड़ने के समान है।

Example :

python
dict = {1:'a', 2:'b', 3:'c'}

# update
dict[1] = 'd'

# new element
dict[4] = 'e'

5. Deleting dictionary element :

डिक्शनरी से element हटाने के दो तरीके हैं –

  1. del statement
  2. pop function

Syntax 1 :

python
del <dictionary name>[<key>]

Example :

python
del cricket[2]
⚠️ NOTE : यदि key dictionary में नहीं है तब error message print होगा।

Syntax 2 :

python
<dictionary name>.pop(<key>)

Example :

python
Cricket.pop(2)
📝 NOTE : यह function element delete करने के बाद उसकी value को return भी करता है।

6. Checking existing key :

Membership Operator in तथा not in का प्रयोग करके dictionary में key की उपस्थिति check की जा सकती है।

Syntax :

python
<key> in <dictionary name>
<key> not in <dictionary name>

Example :

python
players = {1:"Tendulkar", 2:"Sachin", 3:"Kapil"}

k = 3
if k in players:
    print("player is", players[k])
else:
    print("player is not exist")

Nested Dictionary :

एक dictionary के अंदर अन्य dictionary होती है उसे nested dictionary कहते हैं। Internal dictionary outer dictionary की value होती है।

Syntax :

python
<dictionary name> = {<key>:{<key>:<value>}, <key>:{<key>:<value>}}

Example :

python
student = {
1:{'name':'Sohan','mark':32},
2:{'name':'Dinesh','mark':40},
3:{'name':'Mohan','mark':42}
}

print(student[1]['name'])

# Output :
# Sohan

Functions of Dictionary :

1. len()डिक्शनरी की key को count करने के लिए प्रयोग किया जाता है।
Syntax
python
len(<dictionary name>)
Example
python
dic = {1:'abc', 2:'def', 3:'ghi'}
print(len(dic))

# Output :
# 3
2. clear()डिक्शनरी के सभी element हटाने के लिए प्रयोग किया जाता है।
Syntax
python
<dictionary name>.clear()
Example
python
dic.clear()
3. get()इस function का प्रयोग key द्वारा value प्राप्त करने के लिए किया जाता है।

यह function दो argument लेता है: 1. key, 2. message

Syntax
python
<dictionary name>.get(<key>, <message>)
Example
python
v = dic.get(4, "key does not exist")
print(v)
4. has_key()यह function dictionary में key की presence check करता है तथा Boolean value return करता है।
Syntax
python
<dictionary name>.has_key(<key>)
Example
python
v = dic.has_key(3)
print(v)

# Output :
# True
5. items()यह function dictionary की सभी key:value pair को tuple में return करता है।
Syntax
python
<dictionary name>.items()
Example
python
dic.items()

# Output :
# dict_items([(1,'abc'), (2,'def'), (3,'ghi')])
6. keys()यह function dictionary की सभी key को return करता है।
📝 NOTE : Key list के रूप में return होती हैं।
Syntax
python
<dictionary name>.keys()
Example
python
dic.keys()

# Output :
# dict_keys([1,2,3])
7. values()यह function dictionary की सभी value को return करता है।
📝 NOTE : Value list के रूप में return होती है।
Syntax
python
<dictionary name>.values()
Example
python
dic.values()

# Output :
# dict_values(['abc','def','ghi'])
8. update()यह function एक dictionary में दूसरी dictionary को जोड़ देता है।
Syntax
python
<original dictionary>.update(<new dictionary>)
Example
python
Cricket.update(players)

players dictionary के elements को Cricket dictionary में जोड़ दिया जाएगा।

Practice Questions :

1

एक dictionary student बनाइए जिसमें name, age और class store हो, और उसे print कीजिए।

Create a dictionary student with name, age, and class, and print it.

2

एक dictionary marks बनाइए और किसी एक subject के marks को access करके print कीजिए।

Create a dictionary marks and print the marks of a specific subject.

3

एक existing dictionary में किसी key की value को update कीजिए।

Update the value of an existing key in a dictionary.

4

एक dictionary में नया key-value pair जोड़िए।

Add a new key-value pair to a dictionary.

5

update() method का उपयोग करके dictionary में multiple values add या update कीजिए।

Use the update() method to add or update multiple values in a dictionary.

6

Loop का उपयोग करके dictionary के सभी key-value pairs print कीजिए।

Use a loop to print all key-value pairs of a dictionary.

7

यह जांचिए कि कोई key dictionary में मौजूद है या नहीं।

Check whether a key exists in a dictionary or not.

8

pop() method का उपयोग करके किसी एक element को delete कीजिए।

Use the pop() method to delete an element from a dictionary.

9

एक nested dictionary बनाइए जिसमें 2 students की details store हों।

Create a nested dictionary to store details of two students.

10

एक dictionary बनाइए जिसमें numbers हों और सबसे बड़ी (maximum) value निकालिए।

Create a dictionary with numbers and find the maximum value.

Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.