„Python“ žodynas (su pavyzdžiais)

Šioje pamokoje sužinosite viską apie „Python“ žodynus; kaip jie kuriami, prieinami, pridedami, pašalinami iš jų elementai ir įvairūs įmontuoti metodai.

Vaizdo įrašas: „Python“ žodynai raktų / reikšmės poroms laikyti

„Python“ žodynas yra nesutvarkytas elementų rinkinys. Kiekvienas žodyno elementas turi key/valueporą.

Žodynai yra optimizuoti, kad gautų reikšmes, kai žinomas raktas.

„Python“ žodyno kūrimas

Sukurti žodyną taip pat paprasta, kaip įdėti elementus į garbanotas petnešas, ()atskirtas kableliais.

Elementas turi keyir atitikmenį value, kuris išreiškiamas pora ( raktas: reikšmė ).

Nors reikšmės gali būti bet kokio tipo duomenys ir gali kartotis, klavišai turi būti nekintamo tipo (eilutė, skaičius arba paketas su nekintamais elementais) ir unikalūs.

 # 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')))

Kaip matote iš viršaus, mes taip pat galime sukurti žodyną naudodami integruotą dict()funkciją.

Prieiga prie elementų iš žodyno

Nors indeksas naudojamas prieigai prie kitų duomenų tipų, norint pasiekti vertes, žodynas naudoja keys. Raktus galima naudoti kvadratiniuose skliaustuose ()arba naudojant get()metodą.

Jei mes naudojame laužtinius skliaustus (), KeyErrorpakeliama, jei raktinio žodžio nerandama. Kita vertus, get()metodas grąžinamas, Nonejei raktas nerandamas.

 # 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'))

Rezultatas

 Jackas 26 Nėra „Traceback“ (paskutinis paskutinis skambutis): Failas "", 15 eilutė, atspausdinta (my_dict ('address')) KeyError: 'address'

Žodyno elementų keitimas ir pridėjimas

Žodynai yra kintami. Naudodami priskyrimo operatorių galime pridėti naujų elementų arba pakeisti esamų elementų vertę.

Jei raktas jau yra, esama reikšmė atnaujinama. Jei rakto nėra, į žodyną įtraukiama nauja pora ( raktas: vertė ).

 # 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)

Rezultatas

 („vardas“: „Džekas“, „amžius“: 27) („vardas“: „Džekas“, „amžius“: 27, „adresas“: „Miesto centras“)

Elementų pašalinimas iš žodyno

Tam tikrą žodyno elementą galime pašalinti naudodami pop()metodą. Šis metodas pašalina elementą su pateiktu keyir grąžina value.

popitem()Metodas gali būti naudojamas pašalinti ir grąžinti savavališkai (key, value)elemento pora iš žodyno. Visus elementus galima pašalinti vienu metu, naudojant clear()metodą.

Raktinį delžodį taip pat galime naudoti atskiriems elementams arba pačiam žodynui pašalinti.

 # 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)

Rezultatas

 16 (1: 1, 2: 4, 3: 9, 5: 25) (5, 25) (1: 1, 2: 4, 3: 9) () Traceback (paskutinis paskutinis skambutis): failas "", 30 eilutė, atspausdinta (kvadratai) NameError: pavadinimas „kvadratai“ nėra apibrėžtas

„Python“ žodyno metodai

Su žodynu galimi metodai pateikiami žemiau. Kai kurie iš jų jau buvo naudojami aukščiau pateiktuose pavyzdžiuose.

Metodas apibūdinimas
aišku () Pašalina visus elementus iš žodyno.
kopija () Grąžina negilų žodyno egzempliorių.
nuo raktų (sek ((v)) 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

Built-in funkcijos patinka all(), any(), len(), cmp(), sorted(), ir tt yra dažniausiai naudojamas su žodynų atlikti įvairias užduotis.

Funkcija apibūdinimas
visi () Grįžti, Truejei visi žodyno klavišai yra teisingi (arba jei žodynas tuščias).
bet koks () Grįžkite, Truejei yra koks nors žodyno raktas. Jei žodynas tuščias, grįžkite False.
len () Grąžinkite žodyno ilgį (elementų skaičių).
cmp () Palyginami dviejų žodynų elementai. (Nėra „Python 3“)
rūšiuojamas () Grąžinkite naują rūšiuojamą raktų sąrašą žodyne.

Štai keletas pavyzdžių, kurie naudoja integruotas funkcijas darbui su žodynu.

 # 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))

Rezultatas

 Klaidinga Tiesa 6 (0, 1, 3, 5, 7, 9)

Įdomios straipsniai...