“Python kamus yang dipesan” Kode Jawaban

Python kamus yang dipesan

from collections import OrderedDict

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

Python memesan

>>> # 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

Kamus yang dipesan

# 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

Koleksi Python ke Kamus

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

penghitung 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

Python kamus yang dipesan

>>> # 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

Jawaban yang mirip dengan “Python kamus yang dipesan”

Pertanyaan yang mirip dengan “Python kamus yang dipesan”

Lebih banyak jawaban terkait untuk “Python kamus yang dipesan” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya