Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] - نسخه متنی

David Ascher, Alex Martelli, Anna Ravenscroft

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







Recipe 5.1. Sorting a Dictionary


Credit: Alex Martelli


Problem



You
want to sort a dictionary. This probably means that you want to sort
the keys and then get the values in that same sorted order.


Solution


The simplest approach is exactly the one expressed by the problem
statement: sort the keys, then pick the corresponding values:

def sortedDictValues(adict):
keys = adict.keys( )
keys.sort( )
return [adict[key] for key in keys]


Discussion


The concept of sorting applies only to a collection that has an
orderin other words, a sequence. A mapping, such as a
dictionary, has no order, so it cannot be sorted. And yet,
"How do I sort a dictionary?" is a
frequent, though literally meaningless, question on the Python lists.
More often than not, the question is in fact about sorting some
sequence composed of keys and/or values from the dictionary.

As for the implementation, while one could think of more
sophisticated approaches, it turns out (not unusually, for Python)
that the one shown in the solution, the simplest one, is also
essentially the fastest one. A further slight increase in speed,
about 20%, can be squeezed out in Python 2.3 by replacing the list
comprehension with a map call in the
return statement at the end of the function. For
example:

    return map(adict.get, keys)

Python 2.4, however, is already measurably faster than Python 2.3
with the version in the "Solution"
and gains nothing from this further step. Other variants, such as
using adict._ _getitem_ _ instead of
adict.get, offer no further increase in speed, or
they even slow performance down a little, in both Python 2.3 and 2.4.


See Also


Recipe 5.4 for sorting a
dictionary based on its values rather than on its keys.


/ 394