10.4: Dictionaries and Tuples

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    10.4: Dictionaries and Tuples

    Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair:

    >>> d = {'a':10, 'b':1, 'c':22}
    >>> t = list(d.items())
    >>> print(t)
    [('b', 1), ('a', 10), ('c', 22)]

    As you should expect from a dictionary, the items are in no particular order.

    However, since the list of tuples is a list, and tuples are comparable, we can now sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key:

    >>> d = {'a':10, 'b':1, 'c':22}
    >>> t = list(d.items())
    >>> t
    [('b', 1), ('a', 10), ('c', 22)]
    >>> t.sort()
    >>> t
    [('a', 10), ('b', 1), ('c', 22)]

    The new list is sorted in ascending alphabetical order by the key value.


    This page titled 10.4: Dictionaries and Tuples was last modified on Tue, 01 Dec 2020 03:50:58 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.