Python dict ()

Hàm khởi tạo dict () tạo một từ điển trong Python.

Các dạng khác nhau của hàm dict()tạo là:

 class dict (** kwarg) class dict (ánh xạ, ** kwarg) class dict (có thể lặp lại, ** kwarg)

Lưu ý: **kwarg cho phép bạn lấy số lượng đối số từ khóa tùy ý.

Đối số từ khóa là đối số được đặt trước bởi một số nhận dạng (ví dụ name=:). Do đó, đối số từ khóa của biểu mẫu kwarg=valueđược chuyển cho dict()hàm tạo để tạo từ điển.

dict()không trả về bất kỳ giá trị nào (trả về None).

Ví dụ 1: Tạo Từ điển Chỉ sử dụng các đối số từ khóa

 numbers = dict(x=5, y=0) print('numbers =', numbers) print(type(numbers)) empty = dict() print('empty =', empty) print(type(empty))

Đầu ra

 số = ('y': 0, 'x': 5) rỗng = () 

Ví dụ 2: Tạo từ điển bằng cách sử dụng lặp lại

 # keyword argument is not passed numbers1 = dict((('x', 5), ('y', -5))) print('numbers1 =',numbers1) # keyword argument is also passed numbers2 = dict((('x', 5), ('y', -5)), z=8) print('numbers2 =',numbers2) # zip() creates an iterable in Python 3 numbers3 = dict(dict(zip(('x', 'y', 'z'), (1, 2, 3)))) print('numbers3 =',numbers3)

Đầu ra

 number1 = ('y': -5, 'x': 5 )umbers2 = ('z': 8, 'y': -5, 'x': 5) number3 = ('z': 3, 'y' : 2, 'x': 1)

Ví dụ 3: Tạo từ điển bằng ánh xạ

 numbers1 = dict(('x': 4, 'y': 5)) print('numbers1 =',numbers1) # you don't need to use dict() in above code numbers2 = ('x': 4, 'y': 5) print('numbers2 =',numbers2) # keyword argument is also passed numbers3 = dict(('x': 4, 'y': 5), z=8) print('numbers3 =',numbers3)

Đầu ra

 number1 = ('x': 4, 'y': 5 )umbers2 = ('x': 4, 'y': 5) number3 = ('x': 4, 'z': 8, 'y': 5 )

Đề xuất Đọc: Từ điển Python và cách làm việc với chúng.

thú vị bài viết...