Питхон речник (са примерима)

У овом упутству ћете научити све о Питхон речницима; како се креирају, приступају им, додају, уклањају елементе из њих и разним уграђеним методама.

Видео: Питхон речници за чување парова кључ / вредност

Питхон речник је неуређена колекција предмета. Свака ставка речника има key/valueпар.

Речници су оптимизовани за преузимање вредности када је кључ познат.

Израда Питхон речника

Стварање речника једноставно је попут стављања предмета у завојне заграде ()раздвојене зарезима.

Ставка има а keyи одговарајући valueкоји се изражава као пар ( кључ: вредност ).

Иако вредности могу бити било ког типа података и могу се поновити, кључеви морају бити непроменљивог типа (низ, број или скуп са непроменљивим елементима) и морају бити јединствени.

 # empty dictionary my_dict = () # dictionary with integer keys my_dict = (1: 'apple', 2: 'ball') # dictionary with mixed keys my_dict = ('name': 'John', 1: (2, 4, 3)) # using dict() my_dict = dict((1:'apple', 2:'ball')) # from sequence having each item as a pair my_dict = dict(((1,'apple'), (2,'ball')))

Као што видите одозго, такође можемо да креирамо речник користећи уграђену dict()функцију.

Приступ елементима из речника

Док се индексирање користи са другим типовима података за приступ вредностима, речник користи keys. Кључеви се могу користити или у углатим заградама ()или помоћу get()методе.

Ако користимо углате заграде (), KeyErrorподиже се у случају да кључ није пронађен у речнику. С друге стране, get()метода се враћа Noneако кључ није пронађен.

 # get vs () for retrieving elements my_dict = ('name': 'Jack', 'age': 26) # Output: Jack print(my_dict('name')) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict('address'))

Оутпут

 Јацк 26 Ноне Трацебацк (последњи последњи позив): Датотека "", ред 15, у штампи (ми_дицт ('аддресс')) КеиЕррор: 'аддресс'

Промена и додавање елемената речника

Речници су променљиви. Помоћу оператора доделе можемо додати нове ставке или променити вредност постојећих.

Ако је кључ већ присутан, постојећа вредност се ажурира. У случају да кључ није присутан, нови речник ( кључ: вредност ) се додаје у речник.

 # Changing and adding Dictionary Elements my_dict = ('name': 'Jack', 'age': 26) # update value my_dict('age') = 27 #Output: ('age': 27, 'name': 'Jack') print(my_dict) # add item my_dict('address') = 'Downtown' # Output: ('address': 'Downtown', 'age': 27, 'name': 'Jack') print(my_dict)

Оутпут

 ('наме': 'Јацк', 'аге': 27) ('наме': 'Јацк', 'аге': 27, 'аддресс': 'Довнтовн')

Уклањање елемената из Речника

Помоћу pop()методе можемо уклонити одређену ставку из речника . Ова метода уклања ставку са приложеном keyи враћа value.

popitem()Може да се користи метода за уклањање и врати произвољну (key, value)ставку пар из речника. Све ставке могу се уклонити одједном, користећи clear()методу.

Кључну delреч такође можемо користити за уклањање појединачних предмета или самог речника.

 # Removing elements from a dictionary # create a dictionary squares = (1: 1, 2: 4, 3: 9, 4: 16, 5: 25) # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: (1: 1, 2: 4, 3: 9, 5: 25) print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: (1: 1, 2: 4, 3: 9) print(squares) # remove all items squares.clear() # Output: () print(squares) # delete the dictionary itself del squares # Throws Error print(squares)

Оутпут

 16 (1: 1, 2: 4, 3: 9, 5: 25) (5, 25) (1: 1, 2: 4, 3: 9) () Трацебацк (последњи последњи позив): Датотека „“, ред 30, у испису (квадрати) НамеЕррор: име 'квадрати' није дефинисано

Методе речника Питхон-а

Методе доступне са речником дате су у табели у наставку. Неки од њих су већ коришћени у горњим примерима.

Метод Опис
јасно() Уклања све ставке из речника.
копирај () Враћа плитку копију речника.
кључеви (сек (, в)) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key(,d)) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key(,d)) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key(,d)) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update((other)) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

Here are a few example use cases of these methods.

 # Dictionary Methods marks = ().fromkeys(('Math', 'English', 'Science'), 0) # Output: ('English': 0, 'Math': 0, 'Science': 0) print(marks) for item in marks.items(): print(item) # Output: ('English', 'Math', 'Science') print(list(sorted(marks.keys())))

Output

 ('Math': 0, 'English': 0, 'Science': 0) ('Math', 0) ('English', 0) ('Science', 0) ('English', 'Math', 'Science')

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces ().

Here is an example to make a dictionary with each item being a pair of a number and its square.

 # Dictionary Comprehension squares = (x: x*x for x in range(6)) print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

This code is equivalent to

 squares = () for x in range(6): squares(x) = x*x print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.

 # Dictionary Comprehension with if conditional odd_squares = (x: x*x for x in range(11) if x % 2 == 1) print(odd_squares)

Output

 (1: 1, 3: 9, 5: 25, 7: 49, 9: 81)

To learn more dictionary comprehensions, visit Python Dictionary Comprehension.

Other Dictionary Operations

Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.

 # Membership Test for Dictionary Keys squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares)

Output

 True True False

Iterating Through a Dictionary

We can iterate through each key in a dictionary using a for loop.

 # Iterating through a Dictionary squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) for i in squares: print(squares(i))

Output

 1 9 25 49 81

Dictionary Built-in Functions

Буилт-ин функцијама као што су all(), any(), len(), cmp(), sorted(), итд се обично користе у речницима за обављање различитих послова.

Функција Опис
све() Врати Trueако су сви тастери речника тачни (или ако је речник празан).
било који() Врати Trueако је било који кључ речника тачан. Ако је речник празан, вратите се False.
лен () Врати дужину (број ставки) у речник.
цмп () Поређује ставке два речника. (Није доступно у Питхон 3)
сортирано () Врати нову сортирану листу кључева у речнику.

Ево неколико примера који користе уграђене функције за рад са речником.

 # Dictionary Built-in Functions squares = (0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: (0, 1, 3, 5, 7, 9) print(sorted(squares))

Оутпут

 Тачно тачно 6 (0, 1, 3, 5, 7, 9)

Занимљиви Чланци...