如何从python中的列表中排序字典

时间:2013-05-15 09:17:02

标签: python dictionary

我有这个东西

mydict = OrderedDict({'a':'1', 'd':'2','f':'1', 'i':'2','m':'1', 'k':'2'})

现在假设我有像

这样的列表

l = [i,k]

所以我想根据列表l订购mydict。这样i,k将是前两个项目,然后其他项目保持原始顺序

我想尽可能少地编写代码。在Python中

1 个答案:

答案 0 :(得分:5)

使用itertools中的unique_everseen食谱。

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

>>> from itertools import *
>>> lis = ["i","k"]
>>> mydict = OrderedDict([('a', '1'), ('d', '2'), ('f', '1'), ('i', '2'), ('k', '2'), ('m', '1')])
# A list is used in creating the OrderedDict, a dict would lose initial order
>>> OrderedDict((key,mydict[key]) for key in unique_everseen(chain(lis,mydict)))
OrderedDict([('i', '2'), ('k', '2'), ('a', '1'), ('d', '2'), ('f', '1'), ('m', '1')])