2022. 8. 13.

OrderedDict. ( in Python)

func: Dictionary remembers added order of items.

Ref : https://docs.python.org/3/library/collections.html


Usecase  sample : convert number to roman numerals.


import string
from collections import OrderedDict

def to_roman(num):
maps = OrderedDict([('M', 1000), ('CM', 900), ('D', 500),
('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40),
('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])
res = ''
for k, v in maps.items():
while num >= v:
print(f' {num}, {v}')
res += k
num -= v
return res

print(1988)
print(to_roman(1988))

### output #####
1988 1988, 1000 988, 900 88, 50 38, 10 28, 10 18, 10 8, 5 3, 1 2, 1 1, 1 MCMLXXXVIII