LLI Wiki — My Digital Knowledge Base

Python cheat sheet: dictionaries, lists, tuples and sorting

Iterating dictionaries, accessing keys and values, reverse lookup by value, tuples and sorting with key=float.

A quick reference for Python dictionaries, lists and tuples: iteration, access to keys and values, reverse lookup and sorting.

Dictionaries

d = {'a': 1, 'b': 2, 'c': 3}

list(d)           # ['a', 'b', 'c'] : the keys
list(d.keys())    # ['a', 'b', 'c'] : the keys
list(d.values())  # [1, 2, 3] : the values
list(d.items())   # [('a', 1), ('b', 2), ('c', 3)] : tuples of (key, value)

Iterate over keys and values together:

for key, value in d.items():
    print(key, value)

Find the key that matches a value:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # george

Build a dictionary from a list of pairs:

pairs = [('key1', 'value1'), ('key2', 'value2')]
d = dict(pairs)

Lists and tuples

list1 = ['physics', 'chemistry', 1997, 2000]
mon_tuple = (1, "ok", "olivier")

Sorting

Sort a list of numeric strings by converting each item with float:

b = ["949.0", "1099.0"]
b.sort(key=float)
print(b)  # ['949.0', '1099.0']
Mastodon LLIMastodon SocialFosstodon