Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91894
| References | <37d9de72-b719-45a0-976c-441fc5898741@googlegroups.com> <70489d38-0848-44c4-9a4c-ba2e2e9aa027@googlegroups.com> |
|---|---|
| Date | 2015-06-02 23:42 +0300 |
| Subject | Re: Please help on this sorted function |
| From | Joonas Liik <liik.joonas@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.80.1433277754.13271.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
my_dict = {1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}
# dict.items() returns an iterator that returns pairs of (key, value) pairs
# the key argument to sorted tells sorted what to sort by,
operator.itemgetter is a factory function , itemgetter(1)== lambda
iterable: iterable[1]
sorted_dict = sorted(my_dict.items(), key=itemgetter(1))
# at this moment sorted dict is a generator of key-value tuples in the
right order
sorted_dict = OrderedDict(sorted_dict) # turn the generator in to an actual
dict.
# notice: regular dicts are NOT ORDERED, you need a special type of dict to
preserve the order, hence OrderedDict
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Please help on this sorted function fl <rxjwg98@gmail.com> - 2015-06-02 13:20 -0700
Re: Please help on this sorted function fl <rxjwg98@gmail.com> - 2015-06-02 13:25 -0700
Re: Please help on this sorted function Joonas Liik <liik.joonas@gmail.com> - 2015-06-02 23:42 +0300
Re: Please help on this sorted function Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-06-03 18:21 +1000
Re: Please help on this sorted function Chris Angelico <rosuav@gmail.com> - 2015-06-03 10:01 +1000
Re: Please help on this sorted function Joonas Liik <liik.joonas@gmail.com> - 2015-06-02 23:32 +0300
Re: Please help on this sorted function Gary Herron <gherron@digipen.edu> - 2015-06-02 14:00 -0700
csiph-web