“Bestellter Wörterbuch Python” Code-Antworten

Bestellter Wörterbuch Python

from collections import OrderedDict

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

Python ordnete sich an

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

geordnetes Wörterbuch

# 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

Python -Sammlungen zum Wörterbuch

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

Python -Theke

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

Bestellter Wörterbuch 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

Ähnliche Antworten wie “Bestellter Wörterbuch Python”

Fragen ähnlich wie “Bestellter Wörterbuch Python”

Weitere verwandte Antworten zu “Bestellter Wörterbuch Python” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen