Tutorial by Examples

dictionary = {"Hello": 1234, "World": 5678} print(dictionary["Hello"]) The above code will print 1234. The string "Hello" in this example is called a key. It is used to lookup a value in the dict by placing the key in square brackets. The number 1234 is ...
The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments. dict(a=1, b=2, c=3) # {'a': 1, 'b': 2, 'c': 3} dict([('d', 4), ('e', 5), ('f', 6)]) # {'d': 4, 'e': ...
One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception mydict = {} mydict['not there'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'not there' One way to avoid...
When working with dictionaries, it's often necessary to access all the keys and values in the dictionary, either in a for loop, a list comprehension, or just as a plain list. Given a dictionary like: mydict = { 'a': '1', 'b': '2' } You can get a list of keys using the keys() method: ...
A dictionary is an example of a key value store also known as Mapping in Python. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. As they are primarily used for referencing items by key, they are not sorted. crea...
Available in the standard library as defaultdict from collections import defaultdict d = defaultdict(int) d['key'] # 0 d['key'] = 5 d['key'] # 5 d = defaultdict(lambda: 'empty') d['key'] # 'empty' d['key'] = 'full' ...
You can create an ordered dictionary which will follow a determined order when iterating over the keys in the dictionary. Use OrderedDict from the collections module. This will always return the dictionary elements in the original insertion order when iterated over. from collections import Ordere...
You can use the ** keyword argument unpacking operator to deliver the key-value pairs in a dictionary into a function's arguments. A simplified example from the official documentation: >>> >>> def parrot(voltage, state, action): ... print("This parrot wouldn't", ac...
Consider the following dictionaries: >>> fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"} >>> dog = {'name': "Clifford", 'hands': "paws", 'color': "red"} Python 3.5+ >>> fishdog = {**fish, **dog}...
Like lists and tuples, you can include a trailing comma in your dictionary. role = {"By day": "A typical programmer", "By night": "Still a typical programmer", } PEP 8 dictates that you should leave a space between the trailing comma and the closi...
options = { "x": ["a", "b"], "y": [10, 20, 30] } Given a dictionary such as the one shown above, where there is a list representing a set of values to explore for the corresponding key. Suppose you want to explore "x"="a" w...
If you use a dictionary as an iterator (e.g. in a for statement), it traverses the keys of the dictionary. For example: d = {'a': 1, 'b': 2, 'c':3} for key in d: print(key, d[key]) # c 3 # b 2 # a 1 The same is true when used in a comprehension print([key for key in d]) # ['c', 'b', '...
Rules for creating a dictionary: Every key must be unique (otherwise it will be overridden) Every key must be hashable (can use the hash function to hash it; otherwise TypeError will be thrown) There is no particular order for the keys. # Creating and populating it with values stock = {'egg...
Dictionaries map keys to values. car = {} car["wheels"] = 4 car["color"] = "Red" car["model"] = "Corvette" Dictionary values can be accessed by their keys. print "Little " + car["color"] + " " + car["model&q...

Page 1 of 1