2020年4月25日 星期六

Python - How to sort dictionary? OrderedDict

#Import OrderedDict
from collections import OrderedDict

[OrderedDict Operation]
- Add Key/Value
D=OrderedDict()
D[1]=3
D[7]=1
D[2]=5
D[9]=7
#Dict status  OrderedDict([(1, 3), (7, 1), (2, 5), (9, 7)])

- Change key to Last
>>> D.move_to_end(1)
#Dict status  OrderedDict([(7, 1), (2, 5), (9, 7), (1, 3)])

- Pop Dict Item
>>> D.popitem()
(1, 3)
#Dict status  OrderedDict([(7, 1), (2, 5), (9, 7)])

- Pop first Dict Item
>>> D.popitem(last=False)
(7, 1)
#Dict status OrderedDict([(2, 5), (9, 7)])

2020年4月2日 星期四

Python3 - How to count items in list?

[Method 1] Count item in list.
# Sample list
sl=[1,2,3,1,2,3,4,5,8]  

# Count item 2
sl.count(2)
→ return 2

[Method 2] Count all item in list.
# Import defaultdict
from collections import defaultdict

# Sample list
sl=[1,2,3,1,2,3,4,5,8]   

# Create hash table
ht=defaultdict(int)

# Hash Table Status
defaultdict(<class 'int'>, {})

# Create hash table & count {items: <count>}
for x in sl:
    ht[x]+=1

# Hash Table Status
defaultdict(<class 'int'>, {1: 2, 2: 2, 3: 2, 4: 1, 5: 1, 8: 1})

# How many "2" in list?
ht[2]
→ return 2