Python Dictionaries

Агуулга

Python Dictionaries – Python – Толь Бичиг #

thisdict = {
  "brand""Ford",
  "model""Mustang",
  "year"1964
}

Dictionary – Толь бичиг #

Dictionaries are used to store data values in key:value pairs.

Толь бичгүүдийн өгөгдлийн утгын түлхүүр болон утга хосоор хадгалахад ашигладаг.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Толь бичиг нь дараалалтай*, өөрчлөгдөх боломжтой бөгөөд давхардсан утгуудыг зөвшөөрдөггүй цуглуулга юм.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Python-ийн 3.7 хувилбараас хойш толь бичиг нь дараалалтай болсон. Python 3.6 ба түүнээс өмнөх хувилбаруудад толь бичиг нь дараалалгүй байсан.

Dictionaries are written with curly brackets, and have keys and values:

Толь бичиг нь хээтэй хаалт ашиглан бичигддэг бөгөөд түлхүүрүүд ба утгуудтай байдаг.

Example – Жишээ #

Create and print a dictionary:

Толь бичиг үүсгэж хэвлэх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Dictionary Items – Толь Бичгийн Элементүүд #

Dictionary items are ordered, changeable, and do not allow duplicates.

Толь бичгийн элементүүд дараалалтай, өөрчлөгдөх боломжтой бөгөөд давхардсан утгуудыг зөвшөөрдөггүй.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Толь бичгийн элементүүд нь түлхүүр болон утга хослуулж илэрхийлэгддэг бөгөөд түлхүүрийн нэрийг ашиглан хандаж болно.

Example – Жишээ #

Print the “brand” value of the dictionary:

“brand” утгыг хэвлэх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict["brand"])

Ordered or Unordered? – Дараалалтай эсвэл Дараалалгүй? #

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Python 3.7 хувилбараас хойш толь бичиг дараалалтай болсон. Python 3.6 ба түүнээс өмнөх хувилбаруудад толь бичиг нь дараалалгүй байсан.

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Толь бичиг дараалалтай гэдэг нь элементүүд нь тодорхой дарааллаар байрлаж байгаа бөгөөд энэ дараалал нь өөрчлөгдөхгүй гэсэн үг юм.

Unordered means that the items do not have a defined order, you cannot refer to an item by using an index.

Дараалалгүй гэдэг нь элементүүд тодорхой дарааллаар байрладаггүй, индекс ашиглан элементэд хандах боломжгүй гэсэн үг юм.

Changeable – Өөрчлөгдөх боломжтой  #

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Толь бичгийг өөрчлөгдөх боломжтой, энэ нь толь бичиг үүсгэгдсэний дараа элементүүдийг өөрчлөх, нэмэх эсвэл устгах боломжтой гэсэн үг юм.


Duplicates Not Allowed – Давхардсан Утгуудыг Зөвшөөрдөггүй #

Dictionaries cannot have two items with the same key:

Толь бичиг нь ижил түлхүүртэй хоёр элемент байж болохгүй.

Example – Жишээ #

Duplicate values will overwrite existing values:

Давхардсан утгууд байгаа тохиолдолд сүүлийн утга байна:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)

Dictionary Length – Толь Бичгийн Урт  #

To determine how many items a dictionary has, use the len() function:

Толь бичигт хэдэн элемент байгааг тодорхойлохын тулд len() функцыг ашиглана.

Example – Жишээ #

Print the number of items in the dictionary:

Толь бичгийн элементүүдийн тоог хэвлэх:

print(len(thisdict))

Dictionary Items – Data Types – Толь Бичгийн Элементүүдийн Өгөгдлийн Төрлүүд  #

The values in dictionary items can be of any data type:

Толь бичгийн элементүүдийн утгууд ямар ч өгөгдлийн төрөл байж болно.

Example – Жишээ #

String, int, boolean, and list data types:

Тэмдэгт мөр, бүхэл тоо, буль болон жагсаалтын өгөгдлийн төрлүүд: 

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

type() #

From Python’s perspective, dictionaries are defined as objects with the data type ‘dict’:

Python-ийн үүднээс авч үзвэл толь бичгүүдийг ‘dict’ өгөгдлийн төрөлтэй объект гэж тодорхойлдог.

<class 'dict'>

Example – Жишээ #

Print the data type of a dictionary:

Толь бичгийн өгөгдлийн төрлийг хэвлэх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict))

The dict() Constructor – dict() Конструктор #

It is also possible to use the dict() constructor to make a dictionary.

Толь бичиг үүсгэхийн тулд dict() конструкторыг ашиглах боломжтой.

Example – Жишээ #

Using the dict() method to make a dictionary:

dict() аргыг ашиглан толь бичиг үүсгэх:

thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

Python Collections (Arrays) – Python Цуглуулгууд (Массивууд) #

There are four collection data types in the Python programming language:

Python програмчлалын хэлэнд дөрвөн төрлийн цуглуулгууд байдаг:

  • List is a collection which is ordered and changeable. Allows duplicate members.

List нь дараалалтай бөгөөд өөрчлөгдөх боломжтой цуглуулга. Давхардсан элемент зөвшөөрдөг.

  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Tuple нь дараалалтай бөгөөд өөрчлөгдөх боломжгүй цуглуулга. Давхардсан элемент зөвшөөрдөг.

  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.

Set нь дараалалгүй, өөрчлөгдөх боломжгүй*, индексгүй цуглуулга. Давхардсан элемент зөвшөөрдөггүй.

  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Dictionary нь дараалалтай** бөгөөд өөрчлөгдөх боломжтой цуглуулга. Давхардсан элемент зөвшөөрдөггүй.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

*Set-ийн элементүүд өөрчлөгдөх боломжгүй, гэхдээ элементүүдийг устгаж, шинэ элементүүдийг нэмж болно.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

**Python 3.7 хувилбараас хойш толь бичгүүд дараалалтай болсон. Python 3.6 болон өмнөх хувилбаруудад толь бичгүүд дараалалгүй байсан.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

Цуглуулгын төрлийг сонгохдоо тухайн төрлийн шинж чанаруудыг ойлгох нь чухал юм. Тухайн өгөгдлийн багцад зөв төрлийг сонгох нь утгыг хадгалах, үр ашиг эсвэл аюулгүй байдлыг нэмэгдүүлэхэд ач холбогдолтой байж болно.

Python – Access Dictionary Items – Python – Толь Бичигийн Элементүүдэд Хандах #

 

Accessing Items – Элементүүдэд Хандах  #

You can access the items of a dictionary by referring to its key name, inside square brackets:

Толь бичгийн элементүүдэд түүний түлхүүрийн нэрийг дөрвөлжин хаалтанд ашиглан хандаж болно:

Example – Жишээ #

Get the value of the “model” key:

“model” түлхүүрийн утгыг авах:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same result:

Танд ижил үр дүнг өгөх get()  гэж нэрлэгддэг арга бас байдаг:

Example – Жишээ #

Get the value of the “model” key:

“model” түлхүүрийн утгыг авах:

x = thisdict.get("model")

Get Keys – Түлхүүрүүдийг Авах #

The keys() method will return a list of all the keys in the dictionary.

keys() арга нь толь бичгийн бүх түлхүүрүүдийг жагсаалтаас буцаана.

Example – Жишээ #

Get a list of the keys:

Түлхүүрүүдийн жагсаалтыг авах:

x = thisdict.keys()

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.

Жагсаалтын түлхүүрүүд нь толь бичгийн харагдац бөгөөд толь бичигт өөрчлөлт хийсэн тохиолдолд энэ жагсаалт шинэчлэгдэнэ.

Example – Жишээ #

Add a new item to the original dictionary, and see that the keys list gets updated as well:

Анхны толь бичигт шинэ элемент нэмээд, түлхүүрүүдийн жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) # Өөрчлөлтийн өмнө
car["color"] = "white"
print(x) # Өөрчлөлтийн дараа

Get Values – Утгуудыг Авах  #

The values() method will return a list of all the values in the dictionary.

values() арга нь толь бичгийн бүх утгуудыг жагсаалтаар буцаана.

Example – Жишээ #

Get a list of the values:

Утгуудын жагсаалтыг авах:

x = thisdict.values()

The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.

Утгуудын жагсаалт нь толь бичгийн харагдац бөгөөд толь бичигт өөрчлөлт хийсэн тохиолдолд энэ жагсаалт шинэчлэгдэнэ.

Example – Жишээ #

Make a change in the original dictionary, and see that the values list gets updated as well:

Анхны толь бичигт өөрчлөлт хийж, утгуудын жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) # Өөрчлөлтийн өмнө
car["year"] = 2020
print(x) # Өөрчлөлтийн дараа

Example – Жишээ #

Add a new item to the original dictionary, and see that the values list gets updated as well:

Анхны толь бичигт шинэ элемент нэмээд, утгуудын жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) # Өөрчлөлтийн өмнө
car["color"] = "red"
print(x) # Өөрчлөлтийн дараа

Get Items – Элементүүдийг Авах #

The items() method will return each item in a dictionary, as tuples in a list.

items() арга нь толь бичгийн бүх элементүүдийг tuple хэлбэрээр жагсаалтаар буцаана.

Example – Жишээ #

Get a list of the key:value pairs

Түлхүүр болон утгуудыг хослуулж авах:

x = thisdict.items()

The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

Буцсан жагсаалтын утгууд нь толь бичгийн харагдац бөгөөд толь бичигт өөрчлөлт хийсэн тохиолдолд энэ жагсаалт шинэчлэгдэнэ.

Example – Жишээ #

Make a change in the original dictionary, and see that the items list gets updated as well:

Анхны толь бичигт өөрчлөлт хийж, утгуудын жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) # Өөрчлөлтийн өмнө
car["year"] = 2020
print(x) # Өөрчлөлтийн дараа

Example – Жишээ #

Make a change in the original dictionary, and see that the items list gets updated as well:

Анхны толь бичигт шинэ элемент нэмээд, утгуудын жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change

Get Items – Элементүүдийг Авах #

The items() method will return each item in a dictionary, as tuples in a list.

items() арга нь толь бичгийн бүх элементүүдийг tuple хэлбэрээр жагсаалтаар буцаана.

Example – Жишээ #

Get a list of the key:value pairs

түлхүүр: утга жагсаалт болгож хослуулж авах

x = thisdict.items()

The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

Буцаагдсан жагсаалт нь толь бичгийн харагдац бөгөөд толь бичигт өөрчлөлт хийсэн тохиолдолд энэ жагсаалт шинэчлэгдэнэ.

Example – Жишээ #

Make a change in the original dictionary, and see that the items list gets updated as well:

Анхны толь бичигт өөрчлөлт хийж, элементүүдийн жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change

Example – Жишээ #

Add a new item to the original dictionary, and see that the items list gets updated as well:

Анхны толь бичигт шинэ элемент нэмээд, элементүүдийн жагсаалт шинэчлэгдсэнийг харах:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change

Check if Key Exists – Түлхүүр байгаа эсэхийг шалгах #

To determine if a specified key is present in a dictionary use the in keyword:

Толь бичигт тодорхой түлхүүр байгаа эсэхийг in түлхүүр үгээр шалгах:

Example – Жишээ #

Check if “model” is present in the dictionary:

“model” толь бичигт байгаа эсэхийг шалгах:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Тиймээ, thisdict толь бичигт 'model' түлхүүр байна")

Python – Change Dictionary Items – Python – Толь Бичгийн Элементүүдийг Өөрчлөх #

 

Change Values – Утгуудыг Өөрчлөх #

You can change the value of a specific item by referring to its key name:

Толь бичгийн тодорхой элементүүдийн утгыг түүний түлхүүрийн нэрийг ашиглан өөрчлөх боломжтой:

Example – Жишээ #

Change the “year” to 2018:

“year” утгыг 2018 болгон өөрчлөх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

Update Dictionary – Толь Бичгийг Шинэчлэх #

The update() method will update the dictionary with the items from the given argument.

update() арга нь өгөгдсөн аргументээс толь бичигт элементүүдийг нэмнэ.

The argument must be a dictionary, or an iterable object with key:value pairs.

Аргумент нь толь бичиг эсвэл түлхүүр:утга хосуудтай давтах объект байх ёстой.

Example – Жишээ #

Update the “year” of the car by using the update() method:

Машины “year” утгыг update() аргыг ашиглан шинэчлэх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})

Python – Add Dictionary Items – Python – Толь Бичигт Элементүүд Нэмэх #

 

Adding Items – Элементүүдийг Нэмэх  #

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Толь бичигт элемент нэмэх нь шинэ түлхүүр индексийг ашиглаж, түүнд утга оноох замаар хийгддэг:

Example – Жишээ #

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary – Толь Бичгийг Шинэчлэх  #

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

update() арга нь өгөгдсөн аргументээс толь бичигт элементүүдийг нэмнэ. Хэрэв элемент байхгүй бол нэмэгдэнэ.

The argument must be a dictionary, or an iterable object with key:value pairs.

Аргумент нь толь бичиг эсвэл түлхүүр: утга хосуудтай давтах объект байх ёстой.

Example – Жишээ #

Add a color item to the dictionary by using the update() method:

Толь бичигт “color” элементийг update() аргаар нэмэх:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"color": "red"})

Python – Remove Dictionary Items – Python – Толь Бичгийн Элементүүдийг Устгах #

Removing Items – Элементүүдийг Устгах  #

There are several methods to remove items from a dictionary:

Толь бичгийн элементүүдийг устгах хэд хэдэн арга бий:

Example – Жишээ #

The pop() method removes the item with the specified key name:

pop() арга нь тодорхой түлхүүр нэртэй элементийг устгана:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

Example – Жишээ #

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

popitem() арга нь хамгийн сүүлд нэмэгдсэн элементийг устгана (3.7 хувилбараас өмнө санамсаргүй элемент устгагдана):

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

Example – Жишээ #

The del keyword removes the item with the specified key name:

del түлхүүр нь тодорхой түлхүүр нэртэй элементийг устгана:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

Error example – Алдааны Жишээ  #

The del keyword can also delete the dictionary completely:

del түлхүүр нь толь бичгийг бүхэлд нь устгаж болно:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) # Энэ нь алдаа үүсгэнэ, учир нь "thisdict" аль хэдийн устсан.

Example – Жишээ #

The clear() method empties the dictionary:

clear() арга нь толь бичгийг хоослоно:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Python – Loop Dictionaries – Python – Толь Бичгүүд Давтах #

 

Loop Through a Dictionary – Толь Бичгийн Элемэнтүүдийг Давтах  #

You can loop through a dictionary by using a for loop.

Толь бичигт for давталт ашиглан давтах боломжтой.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Толь бичгийг давтах үед толь бичгийн түлхүүрүүдийг буцаадаг, гэхдээ утгыг буцаах аргууд бас байдаг.

Example – Жишээ #

Print all key names in the dictionary, one by one:

Толь бичгийн бүх түлхүүрийн нэрийг нэг нэгээр нь хэвлэх:

for x in thisdict:
  print(x)

Example – Жишээ #

Print all values in the dictionary, one by one:

Толь бичгийн бүх утгыг нэг нэгээр нь хэвлэх:

for x in thisdict:
  print(thisdict[x])

Example – Жишээ #

You can also use the values() method to return values of a dictionary:

Бас values() аргыг ашиглан толь бичгийн утгуудыг буцаах боломжтой:

for x in thisdict.values():
  print(x)

Example – Жишээ #

You can use the keys() method to return the keys of a dictionary:

keys() аргыг ашиглан толь бичгийн түлхүүрүүдийг буцаах боломжтой:

for x in thisdict.keys():
  print(x)

Example – Жишээ #

Loop through both keys and values, by using the items() method:

items() аргыг ашиглан түлхүүр болон утгуудыг хамтад нь давтах:

for x, y in thisdict.items():
  print(x, y)

Python – Copy Dictionaries – Python – Толь Бичгийг Хуулбарлах #

Copy a Dictionary – Толь Бичгийг Хуулбарлах  #

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

Та dict2 = dict1 гэж бичээд толь бичгийг хуулбарлаж чадахгүй, учир нь dict2 зөвхөн dict1-ийн лавлагаа болно, dict1 дээр хийсэн өөрчлөлтүүд автоматaap dict2-д хийгдэнэ.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Толь бичгийг хуулбарлах хэд хэдэн арга бий, нэг арга нь толь бичигт байх copy() аргыг ашиглах.

Example – Жишээ #

Make a copy of a dictionary with the copy() method:

copy() аргаар толь бичгийг хуулбарлах:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in function dict().

Өөр нэг арга нь dict() функцыг ашиглах.

Example – Жишээ #

Make a copy of a dictionary with the dict() function:

dict() функц ашиглан толь бичгийг хуулбарлах:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict)

Python – Nested Dictionaries – Python – Угсармал Толь Бичгүүд #

Nested Dictionaries – Угсармал Толь Бичгүүд  #

A dictionary can contain dictionaries, this is called nested dictionaries.

Толь бичигт толь бичиг байлгах боломжтой, үүнийг угсармал толь бичиг гэж нэрлэдэг.

Example – Жишээ #

Create a dictionary that contain three dictionaries:

Гурван толь бичиг агуулах толь бичиг үүсгэх:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

Or, if you want to add three dictionaries into a new dictionary:

Эсвэл, гурван толь бичгийг шинэ толь бичигт нэмэхийг хүсвэл:

Example – Жишээ #

Create three dictionaries, then create one dictionary that will contain the other three dictionaries:

Гурван толь бичиг үүсгээд, тэдгээрийг агуулах нэг толь бичиг үүсгэх:

child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}
myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

Access Items in Nested Dictionaries – Угсармал Толь Бичгүүдэд Хандах  #

To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary:

Угсармал толь бичигт элементүүдэд хандахын тулд толь бичгийн нэрийг ашиглан эхлүүлнэ:

Example – Жишээ #

Print the name of child 2:

“child2”-ийн нэр түлхүүрийг хэвлэх:

print(myfamily["child2"]["name"])

Python Dictionary Methods – Python Толь Бичгийн Аргууд #

 

fromkeys() Method #

Example #

Create a dictionary with 3 keys, all with the value 0:

x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)

Definition and Usage #

The fromkeys() method returns a dictionary with the specified keys and the specified value.


Syntax #

dict.fromkeys(keys, value)
 

Parameter Values #

Parameter Description
keys Required. An iterable specifying the keys of the new dictionary
value Optional. The value for all keys. Default value is None

More Examples #

Example #

Same example as above, but without specifying the value:

x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)

setdefault() Method #

Example #

Get the value of the “model” item:

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)

Definition and Usage #

The setdefault() method returns the value of the item with the specified key.

If the key does not exist, insert the key, with the specified value, see example below


Syntax #

dictionary.setdefault(keyname, value)
 

Parameter Values #

Parameter Description
keys Required. An iterable specifying the keys of the new dictionary
value Optional. The value for all keys. Default value is None

More Examples #

Example #

Get the value of the “color” item, if the “color” item does not exist, insert “color” with the value “white”:

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = car.setdefault("color", "white")
print(x)

Dictionary Methods – Толь Бичгийн Аргууд #

Python has a set of built-in methods that you can use on dictionaries.

Python нь толь бичигт ашиглаж болох олон аргуудтай.

Method

Арга

Description

Тайлбар

clear()

Removes all the elements from the dictionary

Толь бичгээс бүх элементүүдийг арилгадаг

copy()

Returns a copy of the dictionary

Толь бичгийн хуулбарыг буцаадаг

fromkeys()

Returns a dictionary with the specified keys and value

Толь бичгийн тодорхойлогдсон түлхүүрүүд болон утга буцаадаг

get()

Returns the value of the specified key

Тодорхойлогдсон түлхүүрийн утгыг буцаадаг

items()

Returns a list containing a tuple for each key value pair

Толь бичгийн бүх түлхүүр-утга хослолуудыг багтаасан tuple жагсаалтыг буцаадаг

keys()

Returns a list containing the dictionary’s keys

Толь бичгийн бүх түлхүүрүүдийг багтаасан жагсаалтыг буцаадаг

pop()

Removes the element with the specified key

Тодорхойлогдсон түлхүүртэй элементийг арилгадаг

popitem()

Removes the last inserted key-value pair

Сүүлд нэмэгдсэн түлхүүр-утга хослолыг арилгадаг

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

Тодорхойлогдсон түлхүүрийн утгыг буцаадаг. Хэрэв түлхүүр байхгүй бол, уг түлхүүрийг тодорхойлогдсон утгатайгаар оруулдаг

update()

Updates the dictionary with the specified key-value pairs

Толь бичгийг тодорхойлогдсон түлхүүр-утга хослолуудаар шинэчилдэг

values()

Returns a list of all the values in the dictionary

Толь бичгийн бүх утгуудыг багтаасан жагсаалтыг буцаадаг

Powered by BetterDocs

Leave a Reply