Python-Dictionary

Trong phần này của hướng dẫn lập trình Python, chúng ta sẽ tìm hiểu chi tiết hơn về dictionary trong Python.

Dictionary là 1 container chứa các cặp key-value. Nó có thể thay đổi và chứa nhiều loại dữ liệu khác nhau. 1 dictionary là 1 tập hợp chưa không có thứ tự. Dictionary trong Python còn được gọi là associative array và hash table trong các ngôn ngữ lập trình khác. Key trong dictionary phải là đối tượng bất biến như string hoặc số. Chúng phải là duy nhất trong dictionary.

Tạo dictionary trong Python

Ví dụ 1: Tạo dictionary trong Python

weekend = { "Sun": "Sunday", "Mon": "Monday" }
vals = dict(one=1, two=2)

capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"

d = { i: object() for i in range(4) }

print(weekend)
print(vals)
print(capitals)
print(d)

Trong ví dụ này, chúng ta tạo 4 dictionary theo 4 cách khác nhau. Sau đó chúng ta in nội dung của dictionary ra màn hình console

weekend = { "Sun": "Sunday", "Mon": "Monday" }

Chúng ta tạo dictionary weekend. Cặp key-value được đặt trong dấu ngoặc {}. Các cặp key-value được phân tách bởi dấu phẩy. Giá trị đầu tiên của cặp key-value là key, tiếp theo là dấu :, sau đó là value.
string “Sun” là key, string “Sunday” là value.

vals = dict(one=1, two=2)

Có thể tạo dictionary bằng function dict()

capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"

Trong cách 3, 1 dictionary captitals rỗng được tạo. 3 cặp được add vào dictionary. Key được đặt trong dấu ngoặc vuông [], value được đặt bên phải toán tử gán =.

d = { i: object() for i in range(4) }

Dictionary được tạo sử dụng dictionary comprehension. Comprehension có 2 phần.
Phần 1 là i: object expression, được thực thi mỗi lần lặp.
Phần 2 là vòng lặp for i in range(4)
Dictionary comprehension tạo dictionary có 4 cặp key-value. Trong đó, key là số 0, 1, 2 và 3, value là object.

Kết quả:

C:\Python\Python37>python.exe test.py
{'Sun': 'Sunday', 'Mon': 'Monday'}
{'one': 1, 'two': 2}
{'svk': 'Bratislava', 'deu': 'Berlin', 'dnk': 'Copenhagen'}
{0: <object object at 0x000002009D747AC0>, 1: <object object at 0x000002009D747AD0>, 2: <object object at 0x000002009D747AE0>, 3: <object object at 0x000002009D747AF0>}

Dictionary comprehension

Dictionary comprehension là cấu trúc lệnh để tạo 1 dictionary từ 1 dictionary khác.

D = { expression for variable in sequence [if condition] }

Dictionary comprehension được đặt giữa 2 dấu ngoặc {}
Dictionary comprehension gồm 3 phần: vòng lặp for, biểu thức điều kiện và biểu thức toán học.

Trong vòng lặp for, chúng ta duyệt dictionary, biểu thức điều kiện là optional (có thể không cần chỉ định). Cuối cùng, expression lọc ra các phần tử thỏa mãn điều kiện if condition, lưu vào dictionary mới. Xem ví dụ dưới đây để hiểu rõ cách implement dictionary dùng dictionary comprehension.

Ví dụ 2: Build dictionary sử dụng dictionary comprehension

capitals = { "Bratislava": 424207, "Vilnius": 556723, "Lisbon": 564657,
             "Riga": 713016, "Jerusalem": 780200, "Warsaw": 1711324,
             "Budapest": 1729040, "Prague": 1241664, "Helsinki": 596661,
             "Yokyo": 13189000, "Madrid": 3233527 }

capitals2 = { key:val for key, val in capitals.items() if val < 1000000 }

print(capitals2)

Trong ví dụ này, chúng ta tạo 1 dictionary capitals

capitals = { "Bratislava": 424207, "Vilnius": 556723, "Lisbon": 564657,
             "Riga": 713016, "Jerusalem": 780200, "Warsaw": 1711324,
             "Budapest": 1729040, "Prague": 1241664, "Helsinki": 596661,
             "Yokyo": 13189000, "Madrid": 3233527 }

Key là tên các thủ đô, còn Value là dân số.

capitals2 = { key:val for key, val in capitals.items() if val < 1000000 }

Tạo ra 1 dictionary capitals2 mới chỉ chứa các phần tử mà dân số nhỏ hơn 1000000.

Kết quả:

C:\Python34>python.exe test.py
{'Bratislava': 424207, 'Vilnius': 556723, 'Riga': 713016, 'Lisbon': 564657, 'Jerusalem': 780200, 'Helsinki': 596661}

Basic operation trên Dictionary

Ví dụ 3: thao tác cơ bản trên dictionary

basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }

basket['bananas'] = 5

print(basket)
print("There are {0} various items in the basket".format(len(basket)))

print(basket['apples'])
basket['apples'] = 8
print(basket['apples'])

print(basket.get('oranges', 'undefined'))
print(basket.get('cherries', 'undefined'))
basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }

Trong ví dụ này, chúng ta define dictionary basket, key là loại quả, value là số lượng quả.

basket['bananas'] = 5

Cặp key-value được add thêm vào dictionary basket. Key là string ‘bananas’, value = 5.

print("There are {0} various items in the basket".format(len(basket)))

Hàm len() được dùng để đếm số lượng cặp key-value trong dictionary basket.

print(basket['apples'])

In value tương ứng với key ‘apples’ ra màn hình console.

basket['apples'] = 8

Modify value tương ứng với key ‘apples’ thành 8.

print(basket.get('oranges', 'undefined'))

Phương thức get() lấy value tương ứng với key ‘oranges’. Nếu không tìm thấy key ‘oranges’ trong dictionary basket, parameter thứ 2 ‘undefined’ được trả về.

print(basket.get('cherries', 'undefined'))

Key ‘cherries’ không tồn tại trong dictionary basket, basket.get() trả về string ‘undefined’.

Kết quả:

C:\Python34>python.exe test.py
{'bananas': 5, 'oranges': 12, 'pears': 5, 'apples': 4}
There are 4 various items in the basket
4
8
12
undefined

Phương thức fromkeys() và setdefault()

Xem ví dụ sau đây để hiểu cách sử dụng 2 phương thức fromkeys() và setdefault()
Ví dụ 4: Sử dụng phương thức fromkeys()

basket = ('oranges', 'pears', 'apples', 'bananas')

fruits = {}.fromkeys(basket, 0)
print(fruits)

fruits['oranges'] = 12
fruits['pears'] = 8
fruits['apples'] = 4

print(fruits.setdefault('oranges', 11))
print(fruits.setdefault('kiwis', 11))

print(fruits)

Phương thức fromkeys() tạo dictionary mới từ 1 list đã tồn tại.
Phương thức setdefault() trả về value nếu key tồn tại trong dictionary. Và ngược lại, phương thức setdefault() insert key-value vào list và trả về value.

basket = ('oranges', 'pears', 'apples', 'bananas')

Định nghĩa list basket

fruits = {}.fromkeys(basket, 0)

Phương thức fromkeys tạo dictionary fruits từ list basket. Các string trong list basket là key trong dictionary.
Value cho các key được khởi tạo là 0.
Chú ý: phương thức fromkeys là class method và cần class name, trong ví dụ này chúng ta sử dụng {}.

fruits['oranges'] = 12
fruits['pears'] = 8
fruits['apples'] = 4

Modify value tương ứng với key.

print(fruits.setdefault('oranges', 11))
print(fruits.setdefault('kiwis', 11))

Key ‘oranges’ đã tồn tại trong dictionary fruits, phương thức setdefault() trả về value của key ‘oranges’.
=> in 12 trong màn hình console.

Key ‘kiwis’ không tồn tại trong dictionary fruits, phương thức setdefault() insert cặp key-value (‘kiwis’-11) vào dictionary fruits, phương thức setdefault() trả về 11.
=> in 11 trong màn hình console.

Kết quả:

C:\Python34>python.exe test.py
{'bananas': 0, 'pears': 0, 'apples': 0, 'oranges': 0}
12
11
{'bananas': 0, 'pears': 8, 'apples': 4, 'kiwis': 11, 'oranges': 12}

Phương thức update()

Ví dụ 5: sử dụng phương thức update() để merge 2 dictionary

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary"}
domains2 = { "us": "United States", "no": "Norway" }

domains.update(domains2)

print(domains)

Merge 2 dictionary sử dụng phương thức update()

Kết quả:

C:\Python34>python.exe test.py
{'hu': 'Hungary', 'us': 'United States', 'no': 'Norway', 'sk': 'Slovakia', 'de': 'Germany'}

Remove phần tử khỏi dictionary

Ví dụ 6: Remove phần tử khỏi dictionary

items = { "coins": 7, "pens": 3, "cups": 2,
    "bags": 1, "bottles": 4, "books": 5 }

print(items)

item = items.pop("coins")
print("Item having value {0} was removed".format(item))

print(items)

del items["bottles"]
print(items)

items.clear()
print(items)

Trong ví dụ, chúng ta define dictionary gồm 6 cặp key-value.

item = items.pop("coins")
print("Item having value {0} was removed".format(item))

Sử dụng phương thức pop() để remove key-value với key “coins” khỏi dictionary. Phương thức pop() trả về value tương ứng với key “coins”.

del items["bottles"]

Sử dụng keyword del để remove key-value (“bottles”-4) khỏi dictionary.

items.clear()

Sử dụng phương thức clear() để remove tất cả cặp key-value khỏi dictionary.

Kết quả:

C:\Python34>python.exe test.py
{'coins': 7, 'books': 5, 'pens': 3, 'bottles': 4, 'bags': 1, 'cups': 2}
Item having value 7 was removed
{'books': 5, 'pens': 3, 'bottles': 4, 'bags': 1, 'cups': 2}
{'books': 5, 'pens': 3, 'bags': 1, 'cups': 2}
{}

Phương thức keys(), values(), items()

Dictionary gồm các gặp key-value. Phương thức keys() trả về list key từ dictionary. Phương thức values() trả về list value. Phương thức items() trả về list tuple key-value.

Ví dụ 7: sử dụng phương thức keys(), values() và items()

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

print(domains.keys())
print(domains.values())
print(domains.items())

print("de" in domains)
print("cz" in domains)
print(domains.keys())

In ra màn hình console list key từ dictionary domains.

print(domains.values()) 

In ra màn hình console list value từ dictionary domains

print(domains.items()) 

Cuối cùng, chúng ta in ra màn hình console 1 list tutple key-value từ dictionary domains

print("de" in domains)
print("cz" in domains)

Với keyword in, Python kiểm tra nếu key “de”, “cz” có tồn tại trong dictionary domains không? Nếu có tồn tại trả về True, không tồn tại trả về False.

Kết quả:

C:\Python34>python.exe test.py
dict_keys(['sk', 'us', 'no', 'hu', 'de'])
dict_values(['Slovakia', 'United States', 'Norway', 'Hungary', 'Germany'])
dict_items([('sk', 'Slovakia'), ('us', 'United States'), ('no', 'Norway'), ('hu', 'Hungary'), ('de', 'Germany')])
True
False

Vòng lặp for

Vòng lặp là khái niệm chung cho tất cả các ngôn ngữ lập trình. Xem ví dụ sau để hiểu cách sử dụng vòng lặp for để duyệt dictionary
Ví dụ 8: Sử dụng vòng lặp for để duyệt dictionary

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway" }

for key in domains:
    print(key)

for val in domains.values():
    print(val)

for k, v in domains.items():
    print(": ".join((k, v)))

Trong ví dụ này, chúng ta sử dụng vòng lặp for để duyệt dictionary, sau đó in ra màn hình key, value, key-value.

for key in domains:
    print(key)

In tất cả các key trong dictionary domains

for val in domains.values():
    print(val)

In tất cả các value trong dictionary domains

for k, v in domains.items():
    print(": ".join((k, v)))

Vòng lặp thứ 3, in ra màn hình console cặp tất cả cặp key-value của dictionary domains.

Kết quả:

C:\Python34>python.exe test.py
de
sk
no
us
hu
Germany
Slovakia
Norway
United States
Hungary
de: Germany
sk: Slovakia
no: Norway
us: United States
hu: Hungary

Kiểm tra key trong dictionary

Sử dụng toán tử in hoặc not in để kiểm tra key có tồn tại trong dictionary không.
Ví dụ 9: Kiểm tra key trong dictionary

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

key = "sk"

if key in domains:
    print("{0} is in the dictionary".format(domains[key]))

Trong ví dụ này, chúng ta sử dụng toán tử in trong biểu thức điều kiện if để kiểm tra key = “sk” có trong dictionary domains hay không. Trong trường hợp này là có, biểu thức điều kiện là True => in ra value “Solvakia”

Kết quả:

C:\Python34>python.exe test.py
Slovakia is in the dictionary

Sort dictionary

Dictionary trong Python là kiểu dữ liệu không theo thứ tự. Ám chỉ rằng không thể sắp xếp dictionary như list. Chúng ta có thể in dictionary ra màn hình theo thứ tự sắp xếp. Trong ví dụ dưới đây, chúng ta tìm hiểu các cách đó.

Ví dụ 10: Hiển thị dictionary theo thứ tự key

items = { "coins": 7, "pens": 3, "cups": 2,
    "bags": 1, "bottles": 4, "books": 5 }

kitems = list(items.keys())
kitems.sort()

for k in kitems:
    print(": ".join((k, str(items[k]))))

Trong ví dụ này, chúng ta sắp xếp theo key và in ra màn hình.

kitems = list(items.keys())

Tạo list kitems key từ dictionary.

kitems.sort()

Sắp xếp list kitems

for k in kitems:
    print(": ".join((k, str(items[k]))))

Sử dụng vòng for duyệt list kitems, in giá trị key cùng với value tương ứng ở dictionary.

Kết quả:

C:\Python34>python.exe test.py
bags: 1
books: 5
bottles: 4
coins: 7
cups: 2
pens: 3

Ví dụ 11: Sử dụng sorted() để sắp xếp key dictionary

items = { "coins": 7, "pens": 3, "cups": 2,
    "bags": 1, "bottles": 4, "books": 5 }

for key in sorted(items.keys()):
    print("%{0}: {1}".format(key, items[key]))

print("###############")

for key in sorted(items.keys(), reverse=True):
    print("{0}: {1}".format(key, items[key]))

Trong ví dụ này, chúng ta sử dụng sorted() để sắp xếp key dictionary theo thứ tự tăng dần, giảm dần.

for key in sorted(items.keys()):
    print("%{0}: {1}".format(key, items[key]))

Trong vòng lặp for, chúng ta in ra key (được sắp xếp tăng dần) và value tương ứng trong dictionary items.

for key in sorted(items.keys(), reverse=True):
    print("{0}: {1}".format(key, items[key]))

Trong vòng lặp for, chúng ta in ra key (được sắp xếp giảm dần) và value tương ứng trong dictionary items.
Chú ý: loại sắp xếp được chỉ định bằng parameter reverse (True: giảm dần, False (default): tăng dần)

Kết quả:

C:\Python34>python.exe test.py
%bags: 1
%books: 5
%bottles: 4
%coins: 7
%cups: 2
%pens: 3
###############
pens: 3
cups: 2
coins: 7
bottles: 4
books: 5
bags: 1

Ví dụ 12: Sắp xếp theo value

items = { "coins": 7, "pens": 3, "cups": 2,
    "bags": 1, "bottles": 4, "books": 5 }

for key, value in sorted(items.items(), key=lambda pair: pair[1]):

    print("{0}: {1}".format(key, value))

print("###############")

for key, value in sorted(items.items(), key=lambda pair: pair[1], reverse=True):

    print("{0}: {1}".format(key, value))

Trong ví dụ này, chúng ta sắp xếp theo value theo thứ tự tăng dần, giảm dần

for key, value in sorted(items.items(), key=lambda pair: pair[1]):
    print("{0}: {1}".format(key, value))

Sắp xếp theo value, in cặp key-value ra màn hình console

Kết quả:

C:\Python34>python.exe test.py
bags: 1
cups: 2
pens: 3
bottles: 4
books: 5
coins: 7
###############
coins: 7
books: 5
bottles: 4
pens: 3
cups: 2
bags: 1

Be the first to comment

Leave a Reply