Python Sözlüğü (Örneklerle)

Bu eğitimde Python sözlükleri hakkında her şeyi öğreneceksiniz; nasıl yaratıldıkları, bunlara erişme, ekleme, çıkarma ve çeşitli yerleşik yöntemler.

Video: Anahtar / değer Çiftlerini Saklamak için Python Sözlükleri

Python sözlüğü, sıralanmamış bir öğe koleksiyonudur. Bir sözlüğün her öğesinin bir key/valueçifti vardır.

Sözlükler, anahtar bilindiğinde değerleri almak için optimize edilmiştir.

Python Sözlüğü Oluşturma

Sözlük oluşturmak, öğeleri ()virgülle ayrılmış küme ayraçlarının içine yerleştirmek kadar basittir .

Bir öğenin, bir çift ​​olarak ifade edilen ( anahtar: değer ) a keyve karşılık gelen valuebir değeri vardır .

Değerler herhangi bir veri türünde olabilir ve tekrarlanabilirken, anahtarlar değişmez tipte (değişmez öğelerle dize, sayı veya başlık) ve benzersiz olmalıdır.

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

Yukarıdan da görebileceğiniz gibi, yerleşik dict()işlevi kullanarak bir sözlük de oluşturabiliriz .

Öğelere Sözlükten Erişme

Değerlere erişmek için diğer veri türleri ile indeksleme kullanılırken, bir sözlük kullanır keys. Tuşlar, köşeli parantez içinde ()veya get()yöntemle kullanılabilir.

Biz köşeli parantez kullanırsanız (), KeyErroranahtar sözlükte bulunmazsa bu durumda yükseltilir. Öte yandan, anahtar bulunmazsa get()yöntem geri döner 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'))

Çıktı

 Jack 26 Yok Traceback (en son çağrı): Dosya "", satır 15, baskıda (my_dict ('adres')) KeyError: 'adres'

Sözlük öğelerini değiştirme ve ekleme

Sözlükler değiştirilebilir. Bir atama operatörü kullanarak yeni öğeler ekleyebilir veya mevcut öğelerin değerini değiştirebiliriz.

Anahtar zaten mevcutsa, mevcut değer güncellenir. Anahtarın olmaması durumunda , sözlüğe yeni bir ( anahtar: değer ) çifti eklenir.

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

Çıktı

 ('ad': 'Jack', 'yaş': 27) ('ad': 'Jack', 'yaş': 27, 'adres': 'Şehir Merkezi')

Sözlükten öğeleri kaldırma

Bir sözlükteki belirli bir öğeyi pop()yöntemi kullanarak kaldırabiliriz . Bu yöntem, sağlanan bir öğeyi kaldırır keyve value.

popitem()Yöntem kaldırmak ve keyfi bir dönüş için kullanılabilir (key, value)sözlükten öğe çifti. Bu clear()yöntem kullanılarak tüm öğeler bir defada çıkarılabilir .

delAnahtar kelimeyi tek tek öğeleri veya sözlüğün tamamını kaldırmak için de kullanabiliriz .

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

Çıktı

 16 (1: 1, 2: 4, 3: 9, 5: 25) (5, 25) (1: 1, 2: 4, 3: 9) () Geri izleme (en son çağrı): Dosya "", satır 30, baskıda (kareler) NameError: ad 'kareler' tanımlı değil

Python Sözlük Yöntemleri

Sözlükle kullanılabilen yöntemler aşağıda tablo halinde verilmiştir. Bazıları yukarıdaki örneklerde zaten kullanılmıştır.

Yöntem Açıklama
açık() Sözlükten tüm öğeleri kaldırır.
kopya () Sözlüğün basit bir kopyasını döndürür.
fromkeys (seq (, 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

Yerleşik işlevleri gibi all(), any(), len(), cmp(), sorted(), vb genellikle farklı görevleri gerçekleştirmek için sözlüklerde kullanılır.

Fonksiyon Açıklama
herşey() TrueSözlüğün tüm tuşları True ise (veya sözlük boşsa) dönün .
hiç() TrueSözlüğün herhangi bir tuşu doğruysa dön . Sözlük boşsa geri dön False.
len () Sözlükteki uzunluğu (öğe sayısı) döndürür.
cmp () İki sözlüğün öğelerini karşılaştırır. (Python 3'te mevcut değildir)
sıralanmış () Sözlükte sıralı yeni bir anahtar listesi döndürür.

Bir sözlükle çalışmak için yerleşik işlevleri kullanan bazı örnekler.

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

Çıktı

 Yanlış Doğru 6 (0, 1, 3, 5, 7, 9)

Ilginç makaleler...