user2330497
user2330497

Reputation: 419

How to order the dictionary from list in python

I have this things

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

Now suppose i have the list like

l = [i,k]

So i want to order the mydict based on the list l. so that i,k will be the first two items and then other items stay as in their original order

I want to do this in as minimal coding as possible. in Python

Upvotes: 2

Views: 145

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

Using the unique_everseen recipe from itertools.

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')])

Upvotes: 5

Related Questions