OrderedDict-ga kalitlarni o'chirib, qayta kiritganingizda nima bo'ladi

 bet 8/12 Sana 04.02.2023 Hajmi 136.13 Kb. #1157765
Bog'liq
d.dasturlash

OrderedDict-ga kalitlarni o'chirib, qayta kiritganingizda nima bo'ladi

# deleting a key from an OrderedDict
ordered_vehicle.pop('bicycle')
for key,value in ordered_vehicle.items():
print(key,value)

#> car BMW

#> bike harley davison
Kalitni qayta kiritishda u yangi yozuv sifatida qabul qilinadi.
# Reinserting the same key and print
ordered_vehicle['bicycle']='hercules'
for key,value in ordered_vehicle.items():
print(key,value)
#> car BMW
#> bike harley davison
#> bicycle hercules
Velosipedni eng oxirida ko'rishingiz mumkin, kalitni o'chirib tashlaganimizda tartib o'zgargan.
Bajarilishi mumkin bo'lgan bir nechta foydali buyruqlar mavjud. Biz ehtiyojga qarab saralash funktsiyalarini bajarishimiz mumkin

OrderedDict yordamida saralash

Agar siz elementlarni qiymatlarining ortib borayotgan tartibida saralashni xohlasangiz nima bo'ladi? Bu sizga ma'lumotlarni tahlil qilishda yordam beradi
Elementlarni KEY bo'yicha tartiblang (o'sish tartibida)
# Sorting items in ascending order of their keys
drinks = {'coke':5,'apple juice':2,'pepsi':10}
OrderedDict(sorted(drinks.items(), key=lambda t: t[0]))

#> OrderedDict([('apple juice', 2), ('coke', 5), ('pepsi', 10)])

Juftlarni VALUE bo‘yicha tartiblang (o‘sish tartibida)

# Sorting according to values

OrderedDict(sorted(drinks.items(), key=lambda t: t[1]))

#> OrderedDict([('apple juice', 2), ('coke', 5), ('pepsi', 10)])

Lug'atni kalit qatorining uzunligi bo'yicha tartiblang (o'sish tartibida)
# Sorting according to length of key string
OrderedDict(sorted(drinks.items(), key=lambda t: len(t[0])))
#> OrderedDict([('coke', 5), ('pepsi', 10), ('apple juice', 2)])