To’plamlar haqida ma’lumot. II. Asosiy qism


Download 136.13 Kb.
bet12/12
Sana04.02.2023
Hajmi136.13 Kb.
#1157765
1   ...   4   5   6   7   8   9   10   11   12
Bog'liq
d.dasturlash

UserDict


Bu lug'atlar uchun o'rash sinfidir. Sintaksis, funktsiyalar UserList va UserString ga o'xshaydi.
sintaksis:collections.UserDict([data])
Biz UserDict ma'lumotlar atributida saqlanadigan argument sifatida lug'atni beramiz.
# importing UserDict
from collections import UserDict
my_dict={'red':'5','white':2,'black':1}

# Creating an UserDict


user_dict = UserDict(my_dict)
print(user_dict.data)

#> {'red': '5', 'white': 2, 'black': 1}




UserDict qanday ishlatilishi mumkin


UserDictehtiyojlaringizga mos ravishda o'zgartirilgan lug'at yaratish imkonini beradi. Keling, o'rnatilgan usulning funksionalligini bekor qilish uchun UserDict dan qanday foydalanish mumkinligini ko'rib chiqaylik. Quyidagi kod kalit-qiymat juftligini o'chirishni oldini oladi.
# Creating a Dictionary where deletion of an is not allowed
class user_dict(UserDict):
# Function to stop delete/pop
def pop(self, s = None):
raise RuntimeError("Not Authorised to delete")

data = user_dict({'red':'5','white':2,'black':1})



# try to delete a item
data.pop(1)

#> ---------------------------------------------------------------------------

RuntimeError Traceback (most recent call last)

<ipython-input-16-2e576a68d2ad> in <module>


12
13 #try to delete a item
---> 14 data.pop(1)

<ipython-input-16-2e576a68d2ad> in pop(self, s)


5 def pop(self, s = None):
6
----> 7 raise RuntimeError("Not Authorised to delete")
8
9

RuntimeError: Not Authorised to delete



Siz RunTimeError xabarini olasiz. Agar siz ma'lumotlarni yo'qotishni xohlamasangiz, bu yordam beradi.
Agar ba'zi kalitlar keraksiz qiymatlarga ega bo'lsa va ularni nol yoki "0" bilan almashtirish kerak bo'lsa-chi? Xuddi shu maqsadda Userdict-dan qanday foydalanish haqida quyidagi misollarni ko'ring.
class user_dict(UserDict):
def replace(self,key):
self[key]='0'

file= user_dict({'red':'5','white':2,'black':1,'blue':4567890})

# Delete 'blue' and 'yellow'
for i in ['blue','yellow']:
file.replace(i)

print(file)


#> {'red': '5', 'white': 2, 'black': 1, 'blue': '0', 'yellow': '0'}

Keraksiz qiymatlari bo'lgan maydon 0 bilan almashtirildi. Bular UserDict sizga kerakli funksiyalarga ega lug'at yaratish imkonini beruvchi oddiy misollardir.Bu kollektsiyalar modulidagi barcha konteyner ma'lumotlar turlari. Ular katta ma'lumotlar to'plamida foydalanilganda samaradorlikni sezilarli darajada oshiradi.
Download 136.13 Kb.

Do'stlaringiz bilan baham:
1   ...   4   5   6   7   8   9   10   11   12




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling