wiki:python/Types/dict


See also:

collections/defaultdict
locals
vars


Python Doc: Mapping Types
Python Tutorial


Prüfen, ob einer von mehreren Schlüsseln in Dictionary
d.setdefault(x, []).append(y)
Search a Python Dictionary Both Ways

Dictionaries modellieren Scopes and namespaces:
Re: Blöde Frage zu "Strings sind nicht veränderbar"
Re: Variable in Rechnung

Check if one of several keys exist in dictionary

>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> not set(('four', 'one', 'zero')).isdisjoint(d)
True
>>> any(name in d for name in ('four', 'one', 'zero'))
True

Create a dictionary

From iterable

>>> dict.fromkeys(['apple', 'pear', 'lemon'], 0)
{'apple': 0, 'lemon': 0, 'pear': 0}

>>> dict((('apple', 3), ('pear', 5), ('lemon', 2)))
{'lemon': 2, 'pear': 5, 'apple': 3}

>>> dict(zip(('apple', 'pear', 'lemon'), (3, 5, 2)))
{'lemon': 2, 'pear': 5, 'apple': 3}

>>> dict(('a1', 'b2', 'c3'))
{'a': '1', 'b': '2', 'c': '3'}

>>> i = (('my_house', 'awesome'), ('your_house', 'dump'), ('my_car', 'incredible'), ('your_car', 'no comment'))
>>> dict((key, value) for key, value in i if key.startswith('my'))
{'my_house': 'awesome', 'my_car': 'incredible'}

Using a template

Re: Datenstruktur eines dict() importieren

>>> TEMPLATE = [
... ('product', str),
... ('price', float),
... ('stock', int)
... ]
>>> data = [['Milk', '0.99', '24'], ['Bread', '3.79', '8']]
>>> [dict((k, f(v)) for ((k, f), v) in zip(TEMPLATE, row)) for row in data]
[{'product': 'Milk', 'price': 0.99, 'stock': 24}, {'product': 'Bread', 'price': 3.79, 'stock': 8}]

Dictionary comprehension

>>> d = {'spam': '', 'eggs': 1, 'apples': 0}
>>> {key: value for key, value in d.items() if value}
{'eggs': 1}

Get keys and values in two lists sorted the same way

Kann man sich auf dictionary Unordnung verlassen?

>>> d = {'a': 'A', 'b': 'B', 'c': 'C'}
>>> keys, values = zip(*d.items())
>>> keys
['a', 'c', 'b']
>>> values
['A', 'C', 'B']

is equivalent to

>>> keys, values = d.keys(), d.values()
>>> keys
['a', 'c', 'b']
>>> values
['A', 'C', 'B']
Last modified 4 years ago Last modified on Oct 16, 2015, 6:06:39 PM