“Dictionnaire ordonné Python” Réponses codées

Dictionnaire ordonné Python

from collections import OrderedDict

# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
Delta Sierra

Python ordonnédict

>>> # 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)])
rebellion

dictionnaire ordonné

# ordered dictionary
#Regular Dictionary
d = {'apple':1, 'oranges':2, 'bananas':3}
d['grapes'] = 4
print(d)

#Output:
# {'apple': 1, 'bananas': 3, 'grapes': 4, 'oranges': 2}

#Ordered Dictionary
from collections import OrderedDict
d = OrderedDict({'apple':1, 'oranges':2, 'bananas':3})
d['grapes'] = 4
print(d)

# OrderedDict([('apple', 1), ('oranges', 2), ('bananas', 3), ('grapes', 4)])
Impossible Impala

Collections Python au dictionnaire

list = ["a","c","c","a","b","a","a","b","c"]
cnt = Counter(list)
od = OrderedDict(cnt.most_common())
for key, value in od.items():
    print(key, value)
Cheerful Cormorant

compteur python

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
Foolish Flamingo

Dictionnaire ordonné Python

>>> # 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)])
Vast Vendace

Réponses similaires à “Dictionnaire ordonné Python”

Questions similaires à “Dictionnaire ordonné Python”

Plus de réponses similaires à “Dictionnaire ordonné Python” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code