Python Ordered Dictionary
from collections import OrderedDict
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
Python Ordered Dictionary
from collections import OrderedDict
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
collections
LIST: Can store duplicate values,Keeps the insertion order.
- ArrayList not syncronized, array based class
- LinkedList not synchronized, doubly linked
- Vector is synchronized, thread safe
SET: Can only store unique values,And does not maintain order
- HashSet can have null, order is not guaranteed
- LinkedHashSet can have null and keeps the order
- TreeSet sorts the order and don't accept null
QUQUE :Accepts duplicates, Doesn't have index num,
First in first our order.
MAP:is a (key-value format)
and keys are always unique,
and value can be duplicated.
- HashTable don't have null key, sychronized(thread-safe)
- LinkedHashMap can have null key, keeps order
- HasHMap can have null key, order is not guaranteed
- TreeMap doesn't have null key and keys are sorted
Examples
■ I have used TreeSet to print dropdown list in for
non duplicate values and ascending order
■ I have used HashMaps to compare values from
a database with expected values
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)]
what type of collections used
Depending on the data that I am working with, I use
Arrays, Lists, Sets, Maps.
collections
import collections
numShoes = int(raw_input())
shoes = collections.Counter(map(int, raw_input().split()))
numCust = int(raw_input())
income = 0
for i in range(numCust):
size, price = map(int, raw_input().split())
if shoes[size]:
income += price
shoes[size] -= 1
print income
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us