Hướng dẫn python defaultdict vs ordereddict - python defaultdict so với Orderdict

test = ('Hello', 24, 'M')  
print(test)  
3 và
test = ('Hello', 24, 'M')  
print(test)  
4 đều là các lớp con của
test = ('Hello', 24, 'M')  
print(test)  
5. Họ có cách sử dụng khác nhau.

Đặt hàng

test = ('Hello', 24, 'M')  
print(test)  
3 giữ các yếu tố theo thứ tự mà chúng đã ở khi chúng được đưa vào lần đầu tiên. keeps the elements in the order that they were in when they were first inserted.

Nếu chúng ta loại bỏ một phần tử và bổ sung lại nó, phần tử sẽ được đẩy ra phía sau. Nếu một yếu tố khóa thay đổi, vị trí không thay đổi.

Mã số

from collections import OrderedDict

mydict = OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])

for k in mydict.items():

print(k)

print('\n')

mydict.pop('b')

mydict['b'] = '2'

for k in mydict.items():

print(k)

Trong mã trên, chúng tôi đã tạo ra một

test = ('Hello', 24, 'M')  
print(test)  
3, thêm các phần tử vào nó, và sau đó in chúng. Sau đó, chúng tôi đã loại bỏ một mục và lấy lại nó trong
test = ('Hello', 24, 'M')  
print(test)  
5. Bây giờ nó ở chỉ số cuối cùng vì thứ tự nhập đã thay đổi.

DefaultDict

A

test = ('Hello', 24, 'M')  
print(test)  
4 là một lớp con hữu ích mà không làm tăng ngoại lệ
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
0 khi cố gắng truy cập khóa không xác định. Tuy nhiên, bạn phải xác định một chức năng xác định những gì bạn muốn xảy ra khi một khóa được tìm kiếm không tồn tại. Hãy nhìn vào một ví dụ:
test = ('Hello', 24, 'M')  
print(test)  
4
is a useful subclass that doesn’t raise a
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
0 exception when trying to access an undefined key. However, you must define a function that defines what you want to happen when a key is searched for that doesn’t exist. Let’s look at an example:

Mã số

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

Trong mã trên, chúng tôi đã tạo ra một

test = ('Hello', 24, 'M')  
print(test)  
3, thêm các phần tử vào nó, và sau đó in chúng. Sau đó, chúng tôi đã loại bỏ một mục và lấy lại nó trong
test = ('Hello', 24, 'M')  
print(test)  
5. Bây giờ nó ở chỉ số cuối cùng vì thứ tự nhập đã thay đổi.

DefaultDict

A

test = ('Hello', 24, 'M')  
print(test)  
4 là một lớp con hữu ích mà không làm tăng ngoại lệ
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
0 khi cố gắng truy cập khóa không xác định. Tuy nhiên, bạn phải xác định một chức năng xác định những gì bạn muốn xảy ra khi một khóa được tìm kiếm không tồn tại. Hãy nhìn vào một ví dụ:



Module collection trong Python được định nghĩa là một bộ chứa được sử dụng để lưu trữ các bộ sưu tập dữ liệu, ví dụ: list, dict, set và tuple,... Nó được giới thiệu để cải thiện các chức năng của bộ chứa bộ sưu tập tích hợp. được định nghĩa là một bộ chứa được sử dụng để lưu trữ các bộ sưu tập dữ liệu, ví dụ: list, dict, set và tuple,... Nó được giới thiệu để cải thiện các chức năng của bộ chứa bộ sưu tập tích hợp.

Nội dung chính ShowShow

  • Hàm namedtuple()
  • Hàm OrderedDict()
  • Hàm defaultdict()
  • Hàm Counter()
  • Hàm deque()
  • Python OrderedDict
  • Python OrderedDict Examples
  • Creating OrderedDict object
  • Adding, Replacing, Removing items from OrderedDict
  • OrderedDict move_to_end example
  • OrderedDict popitem example
  • OrderedDict Reverse Iteration
  • OrderedDict Equality Tests Example
  • Kết thúc
  • Đọc liên quan

Tài liệu chính thức   cho OrderedDict

Mô-đun Python trong tuần:  OrderedDict

Hàm namedtuple()

Hàm OrderedDict()

test = ('Hello', 24, 'M')  
print(test)  

Hàm defaultdict()

Hàm OrderedDict()

Hàm defaultdict()

import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 

Hàm defaultdict()

Hàm defaultdict()

Hàm Counter()

from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])

Kết quả:

Hàm Counter()

Python Count() là một lớp con của đối tượng từ điển giúp đếm các đối tượng hashtable.

from collections import Counter
c = Counter()
list = [1, 2, 3, 4, 5, 7, 8, 5, 9, 6, 10]
Counter(list)
Counter({1:5, 2:4})
list = [1, 2, 4, 7, 5, 1, 6, 7, 6, 9, 1]
c = Counter(list)
print(c[1])

Kết quả:

Hàm deque()

Python deque() là hàng đợi hai đầu cho phép chúng ta thêm và xóa các phần tử ở cả hai đầu.

from collections import deque
list = ["x", "y", "z"]
deq = deque(list)
print(deq)

Kết quả:



Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted. A regular dictionary doesn’t track the insertion order. So when iterating over it, items are returned in an arbitrary order. When we want to make sure that items are returned in the order they were inserted, we can use OrderedDict.

Nội dung chính

  • Python OrderedDict
  • Python OrderedDict Examples
  • Creating OrderedDict object
  • Adding, Replacing, Removing items from OrderedDict
  • OrderedDict move_to_end example
  • OrderedDict popitem example
  • OrderedDict Reverse Iteration
  • OrderedDict Equality Tests Example
  • Kết thúc
  • Đọc liên quan

Python OrderedDict

  • Python OrderedDict Examples
  • Creating OrderedDict object
  • Adding, Replacing, Removing items from OrderedDict
  • OrderedDict move_to_end example
  • OrderedDict popitem exampleFIFO order. It accepts a boolean argument
    import collections  
    d1 = collections.OrderedDict()  
    d1['A'] = 10  
    d1['C'] = 12  
    d1['B'] = 11  
    d1['D'] = 13  
    d1['C'] = 15  
      
    for k, v in d1.items():  
        print (k, v) 
    
    8, if it’s set to
    import collections  
    d1 = collections.OrderedDict()  
    d1['A'] = 10  
    d1['C'] = 12  
    d1['B'] = 11  
    d1['D'] = 13  
    d1['C'] = 15  
      
    for k, v in d1.items():  
        print (k, v) 
    
    9 then items are returned in LIFO order.
  • OrderedDict Reverse Iteration
  • OrderedDict Equality Tests Example
  • Kết thúc
  • Đọc liên quan
  • OrderedDict is part of python collections module.

Python OrderedDict Examples

Creating OrderedDict object

Creating OrderedDict object

from collections import OrderedDict

# creating a simple dict
my_dict = {'kiwi': 4, 'apple': 5, 'cat': 3}

# creating empty ordered dict
ordered_dict = OrderedDict()
print(ordered_dict)

# creating ordered dict from dict
ordered_dict = OrderedDict(my_dict)
print(ordered_dict)

Output:

OrderedDict()
OrderedDict([('kiwi', 4), ('apple', 5), ('cat', 3)])

Adding, Replacing, Removing items from OrderedDict

# adding elements to dict
ordered_dict['dog'] = 3

# replacing a dict key value
ordered_dict['kiwi'] = 10
print(ordered_dict)

# removing and adding a value
ordered_dict.pop('kiwi')
print(ordered_dict)
ordered_dict['kiwi'] = 4
print(ordered_dict)

Output:

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

0

OrderedDict move_to_end example

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

1

Output:

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

2

OrderedDict popitem example

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

3

Output:

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

4

OrderedDict Reverse Iteration

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

5

Output:

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

6

OrderedDict Equality Tests Example

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

7

Output:

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

8

Kết thúc

Đọc liên quan

OrderedDict is part of python collections module.

from collections import defaultdict

def defval():

return 'default value'

mydict = defaultdict(defval)

mydict['a'] = 1

mydict['b'] = 2

mydict['c'] = 3

for k in mydict.items():

print(k)

print('\n')

# if we try to get 'd'

print(mydict['d'])

# with a 'generic' dict this will raise a KeyError exception

print('\n')

# it also add it to the dict

for k in mydict.items():

print(k)

9

We can create an empty

test = ('Hello', 24, 'M')  
print(test)  
3 and add items to it. If we create an OrderedDict by passing a dict argument, then the ordering may be lost because dict doesn’t maintain the insertion order.

test = ('Hello', 24, 'M')  
print(test)  
0

If an item is overwritten in the OrderedDict, it’s position is maintained.

test = ('Hello', 24, 'M')  
print(test)  
1

If an item is deleted and added again, then it moves to the last.sắp xếp của Python . Hàm được sắp xếp có trong các mục của từ điển, đó là danh sách các bộ dữ liệu đại diện cho các cặp khóa của từ điển. Nó sắp xếp chúng và sau đó chuyển chúng vào OrderedDict, thứ sẽ giữ trật tự của chúng. Vì vậy, khi chúng ta đi in ra các khóa và giá trị, chúng theo thứ tự chúng ta mong đợi. Nếu bạn lặp qua một từ điển thông thường (không phải là danh sách các khóa được sắp xếp), thứ tự sẽ thay đổi mọi lúc.

OrderedDict

import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
7 removes the items in FIFO order. It accepts a boolean argument
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
8, if it’s set to
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
9 then items are returned in LIFO order.

We can move an item to the beginning or end of the OrderedDict using

from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])
0 function. It accepts a boolean argument
import collections  
d1 = collections.OrderedDict()  
d1['A'] = 10  
d1['C'] = 12  
d1['B'] = 11  
d1['D'] = 13  
d1['C'] = 15  
  
for k, v in d1.items():  
    print (k, v) 
8, if it’s set to
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])
2 then item is moved to the start of the ordered dict.

From python 3.6 onwards, order is retained for keyword arguments passed to the OrderedDict constructor, refer PEP-468.popitemmove_to_end . Phương thức popitem sẽ trả về và xóa một cặp (khóa, vật phẩm). Phương thức move_to_end sẽ di chuyển một khóa hiện có đến một trong hai đầu của OrderedDict. Mục này sẽ được chuyển sang phải đến cuối nếu đối số cuối cùng cho OrderedDict được đặt thành True (là mặc định) hoặc bắt đầu nếu nó là Sai.

Thật thú vị, OrderedDicts hỗ trợ phép lặp ngược bằng cách sử dụng hàm tích hợp đảo ngược của Python:

test = ('Hello', 24, 'M')  
print(test)  
2

Khá gọn gàng, mặc dù bạn có thể sẽ không cần chức năng đó mỗi ngày.

Kết thúc

Tại thời điểm này, bạn nên sẵn sàng dùng thử OrderedDict cho chính mình. Đó là một bổ sung hữu ích cho bộ công cụ của bạn mà tôi hy vọng bạn sẽ tìm thấy nhiều cách sử dụng trong cơ sở mã của mình.

Đọc liên quan

  • Tài liệu chính thức   cho OrderedDict
  • Mô-đun Python trong tuần:  OrderedDict

4 hữu ích 0 bình luận 9.7k xem chia sẻ 0 bình luận 9.7k xem chia sẻ