“Kamus yang dipesan” Kode Jawaban

Python memesan kamus

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

Ordereddict

# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
 
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
 
for key, value in d.items():
    print(key, value)
 
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
 
for key, value in od.items():
    print(key, value)
Phuong Anh Dang

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

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 “Kamus yang dipesan”

Pertanyaan yang mirip dengan “Kamus yang dipesan”

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

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya