Python Ordered Dictionary
from collections import OrderedDict
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
Python Ordered Dictionary
from collections import OrderedDict
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
python ordereddict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
python counter
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
python collections
# Dictionary where key values default to a list:
a = collections.defaultdict(list)
# Dictionary where key values default to 0:
a = collections.defaultdict(int)
# Dictionary where key values default to another dictionary:
a = collections.defaultdict(dict)
'''
Example:
In a regular dictionary, if you did the following:
a = {}
if a['apple'] == 1:
return True
else:
return False
You'd get an error, because 'apple' does not exist in dictionary.
However, if you use collections:
a = collections.defaultdict(int)
if a['apple'] == 1:
return True
else:
return False
This would not give an error, and False would be returned.
Also, the dictionary would now have the key 'apple' with a
default integer value of 0 inside it.
If you used say, collections.defaultdict(list), the default value
would be an empty list instead of 0.
'''
python counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
python collections
list = [1,2,3,4,1,2,6,7,3,8,1]
Counter(list)
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us