dict va set - turlari
dict - to‘plam turi
set - to‘plam turi
Biz ko‘p o‘rinlarda to‘plam turidan foydalanamiz. To‘plamlarga odatda ta’rif bermaymiz, lekin umumiy holda ma’lum bir narsalarni qamrab oluvchi turga aytamiz. Masalan, u sinfdagi barcha obyektlar bo‘lishi mumkin, yoki o‘quvchilar bo‘lishi mumkin. Ushbu turning qolgan tuple va list turlaridan asosiy farqi, ushbu tur matematikadagi to‘plam tushunchasi bilan bir xil amallarni bajishga yordam berib, ikkita bir xil qiymatni o‘zida saqlamaydi. Quyida bu turning umumiy xususiyatlari:
setturi matematikadagi to‘plamlarni ifodalaydi hamda turli amallarni bajarish uchun bir qancha metodlarni taqdim etadi;tartiblanmagan - uning elementlari umuman biror tartibga ega bo‘lmaydi;
o‘zgartirib bo‘lmaydigan - ichidagi elementlarning qiymatlarini almashtirib bo‘lmaydi;
indeks operatori mavjud emas - tartiblanmagi uchun ham hech qanday indekslash amali mavjud emas, ya’ni uning elementlarini olib ham almashtirib ham bo‘lmaydi;
takrorlanuvchi elementlar mavjud bo‘lmaydi - ikki bir xil qiymatlar mavjud bo‘lmaydi;
faqat heshlash mumkin bo‘lgan turlarni saqlaydi.
Eslatma. Biz haligacha heshlash nima ekanligi haqida umumiy holda aytmadik.
strvatupleturlarning obyektlarini heshlash mumkin, lekindictvalistturi obyektlarini esa mumkin emas. Sodda holda, biz qiymatlarini o‘zgartirib bo‘ladigan obyektlarni heshlay olmaymiz, chunki ularni umumiy holda xotiradagi manzilini saqlaymiz(xatolik bilan aytganda). Lekin,strvatupleturining obyketlarining qiymatlarini indeks bo‘yicha almashtirib bo‘lmaydi.
Bu tur obyektlarni hosil qilishning eng sodda yo‘li jingalak {} qavslardan foydalanamiz va ushbu qavslar ichida esa qiymatlarni vergul bilan ajratgan holda joylashtiramiz. Quyida raqamlar to‘plamini o‘zida saqlovchi dastur matni keltirilgan.
[2]:
digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(digits)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Ushbu turning obyektlariga indeks orqali murojaat qilish mumkin emas:
[1]:
digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(digits[0])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[1], line 2
1 digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
----> 2 print(digits[0])
TypeError: 'set' object is not subscriptable
Qiymatlarini indeks amali orqali o‘zgartirish ham mumkin emas:
[2]:
digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
digits[0] = 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[2], line 2
1 digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
----> 2 digits[0] = 0
TypeError: 'set' object does not support item assignment
Turli xildagi obyektlarni element sifatida saqlash mumkin:
[3]:
digits = {0, 'nol', 1, 'bir', 2, 3, 4, 5, 6, 7, 8, 9}
print(digits)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'nol', 'bir'}
E’tibor bering, yuqoridagi kodda digits o‘zgaruvchisini chop etganimizda elementlar ketma-ketligi birinchi berilgan ketma-ketlikdan boshqacha chiqdi, chunki bu tur qiymatlarni tartiblanmagan holda saqlaydi. Lekin, xuddi shu qiymatlarni tuple yoki list turida saqlasak unda bu ketma-ketlik o‘zgarmaydi, quyidagicha:
[6]:
digits = (0, 'nol', 1, 'bir', 2, 3, 4, 5, 6, 7, 8, 9)
print(digits)
digits = [0, 'nol', 1, 'bir', 2, 3, 4, 5, 6, 7, 8, 9]
print(digits)
(0, 'nol', 1, 'bir', 2, 3, 4, 5, 6, 7, 8, 9)
[0, 'nol', 1, 'bir', 2, 3, 4, 5, 6, 7, 8, 9]
Eslatma. Biz yuqorida tartib tushunchasi haqida so‘z yuritganimizda,
list,tuplevasetturlarining elementlarini qanday ketma-ketlikda kiritishni nazarda tutyabmiz. Shunga ko‘ra,listvatupleturlari biz bergan tartibni saqlab qoladi, lekinsetunday qilmaydi.
Yana bir list va tuple turdan farqi, agar bo‘sh to‘plam e’lon qilmoqchi bo‘lsak, faqat set() funksiyasidan foydalana olamiz. Agar jingalak {} qavslardan foydalansak, u holda bu tur dict turi bo‘lib qoladi.
[4]:
empty = {}
print(type(empty))
<class 'dict'>
set turi element sifatida list va dict turlari obyektlarini qabul qilmaydi, chunki ularning elementlarini o‘zgartirish mumkin:
[6]:
s = {1, 2, [3, 4, 5], 6, (7, 8), 9}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 1
----> 1 s = {1, 2, [3, 4, 5], 6, (7, 8), 9}
TypeError: unhashable type: 'list'
Ushbu tur obyekti bizga bir qancha metodlarni taqdim etadi:
*.add()- yangi element qo‘shish;
[7]:
s = {1, 2, 3, 4}
s.add(5)
print(s)
{1, 2, 3, 4, 5}
*.clear()- hamma elementlarini o‘chirib yuborish:
[8]:
s = {1, 2, 3, 4}
s.clear()
print(s)
set()
*.copy()- hamma elementlaridan nusxa olib, undan yangisetturi obyektini hosil qiladi:
[11]:
s = {1, 2, 3, 4}
s1 = s.copy()
print("s1=", s1)
s1.add(5)
print("s=", s)
print("s1=", s1)
s1= {1, 2, 3, 4}
s= {1, 2, 3, 4}
s1= {1, 2, 3, 4, 5}
Agar biz *.copy() metodining o‘rniga shunchaki = o‘zlashtirish amalini ishlatib yangi obyektni hosil qilsak, u holda bu ikki obyekt bir joyga murojaat qilayotgan bo‘ladi hamda birining o‘zgarishi ikkinchisiga ta’sir qiladi. Chunki ularning xotiradagi joyi bitta hisoblanadi:
[13]:
s = {1, 2, 3, 4}
s1 = s
print("s1=", s1)
s1.add(5)
print("s=", s)
print("s1=", s1)
s1= {1, 2, 3, 4}
s= {1, 2, 3, 4, 5}
s1= {1, 2, 3, 4, 5}
Mutable va immutable
list
Immutable
tuple,str,set, etc
[105]:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
3
[19]:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
[106]:
set1 = {"abc", 34, True, 40, "male"}
[107]:
myset = {"apple", "banana", "cherry"}
print(type(myset))
<class 'set'>
[109]:
thisset = set(("apple", "banana", "cherry", 'apple')) # note the double round-brackets
print(thisset)
{'cherry', 'banana', 'apple'}
[113]:
thisset = {0, 'orange', "apple", "banana", "cherry", 1}
for x in thisset:
print(x)
0
1
cherry
orange
banana
apple
[116]:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
True
[117]:
thisset = {"apple", "banana", "cherry"}
print("banana" not in thisset)
False
[119]:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
{'orange', 'cherry', 'banana', 'apple'}
[121]:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
{'pineapple', 'papaya', 'mango', 'cherry', 'banana', 'apple'}
[122]:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
{'cherry', 'orange', 'kiwi', 'apple', 'banana'}
[125]:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
{'cherry', 'apple'}
[126]:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
{'cherry', 'apple'}
[127]:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
cherry
{'banana', 'apple'}
[128]:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
set()
[129]:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[129], line 5
1 thisset = {"apple", "banana", "cherry"}
3 del thisset
----> 5 print(thisset)
NameError: name 'thisset' is not defined
setlarni qo‘shish
union()update()intersection()difference()symmetric_difference()
[131]:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
{1, 2, 'a', 3, 'b', 'c'}
[132]:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1 | set2
print(set3)
{1, 2, 'a', 3, 'b', 'c'}
[133]:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1.union(set2, set3, set4)
print(myset)
{1, 2, 'a', 3, 'cherry', 'apple', 'b', 'bananas', 'John', 'c', 'Elena'}
[134]:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1 | set2 | set3 |set4
print(myset)
{1, 2, 'a', 3, 'cherry', 'apple', 'b', 'bananas', 'John', 'c', 'Elena'}
[136]:
x = {"a", "b", "c"}
y = [1, 2, 3]
z = x.union(y)
print(z)
{1, 2, 'a', 3, 'b', 'c'}
[137]:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
{1, 2, 'a', 3, 'b', 'c'}
[138]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.intersection(set2)
print(set3)
{'apple'}
[139]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 & set2
print(set3)
{'apple'}
[140]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.intersection_update(set2)
print(set1)
{'apple'}
[141]:
set1 = {"apple", 1, "banana", 0, "cherry"}
set2 = {False, "google", 1, "apple", 2, True}
set3 = set1.intersection(set2)
print(set3)
{False, 1, 'apple'}
[143]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.difference(set2)
print(set3)
{'cherry', 'banana'}
[144]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 - set2
print(set3)
{'cherry', 'banana'}
[145]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.difference_update(set2)
print(set1)
{'cherry', 'banana'}
[146]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.symmetric_difference(set2)
print(set3)
{'microsoft', 'cherry', 'banana', 'google'}
[50]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 ^ set2
print(set3)
{'microsoft', 'cherry', 'banana', 'google'}
[51]:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.symmetric_difference_update(set2)
print(set1)
{'microsoft', 'cherry', 'banana', 'google'}
dict - lug’at turi
[147]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
[148]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ford
[149]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
[150]:
print(len(thisdict))
3
[152]:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
[153]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
<class 'dict'>
[154]:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
{'name': 'John', 'age': 36, 'country': 'Norway'}
[159]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang
[164]:
x = thisdict.get("model1")
print(x)
None
[165]:
x = thisdict.keys()
x
[165]:
dict_keys(['brand', 'model', 'year'])
[167]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
[168]:
car
[168]:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white'}
[169]:
x = thisdict.values()
print(x)
dict_values(['Ford', 'Mustang', 1964])
[170]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])
[171]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])
[172]:
x = thisdict.items()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
[173]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
[174]:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])
[175]:
for key, value in car.items():
print(key, value)
brand Ford
model Mustang
year 1964
color red
[179]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Yes, 'model' is one of the keys in the thisdict dictionary
[180]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
[ ]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020, 'brand': 'Tiko‘, 'color': 'red'})
print(thisdict)
{'brand': 'Tiko', 'model': 'Mustang', 'year': 2020, 'color': 'red'}
[183]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}
[184]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}
[185]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}
[76]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[76], line 7
1 thisdict = {
2 "brand": "Ford",
3 "model": "Mustang",
4 "year": 1964
5 }
6 del thisdict
----> 7 print(thisdict) #this will cause an error because "thisdict" no longer exists.
NameError: name 'thisdict' is not defined
[77]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
{}
[186]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
brand
model
year
[188]:
for x in thisdict:
print(x, thisdict[x])
brand Ford
model Mustang
year 1964
[189]:
for x in thisdict.values():
print(x)
Ford
Mustang
1964
[190]:
for x in thisdict.keys():
print(x)
brand
model
year
[191]:
for x, y in thisdict.items():
print(x, y)
brand Ford
model Mustang
year 1964
[192]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
[193]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
[87]:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
[88]:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
[194]:
print(myfamily["child2"]["name"])
Tobias
[195]:
for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])
child1
name: Emil
year: 2004
child2
name: Tobias
year: 2007
child3
name: Linus
year: 2011