Horje
Python Ordered Dictionary Code Example
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)])
counter most_common
most_common([n])ΒΆ
Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.
Elements with equal counts are ordered arbitrarily:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
ordered dict
#Update: As of Python 3.7 (and CPython 3.6), standard dict is 
	#guaranteed to preserve order and is more performant than OrderedDict. 
#(For backward compatibility and especially readability, 
	#however, you may wish to continue using OrderedDict.)

>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']

>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']
python counter
sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
c += Counter()                  # remove zero and negative counts




Python

Related
pandas dataframe column names Code Example pandas dataframe column names Code Example
best pyqt5 book Code Example best pyqt5 book Code Example
pandas dataframe unique multiple columns Code Example pandas dataframe unique multiple columns Code Example
python script to read all file names in a folder Code Example python script to read all file names in a folder Code Example
check object attributes python Code Example check object attributes python Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
7