Python dictionaries
Introduction
Create a dictionary
To create a dictionary you need to use curly braces {}
{key:value}
A key must be an immutable object, that is, a number, a string or a tuple will do, but, for example,
a list
will not
You cannot rely on the order of the elements in a dictionary being preserved.
>>> urls = { ... 'Forward': 'https://forward.bike', ... 'Shulz': 'https://velodrive.ru', ... 'Stels': 'https://velosklad.ru', ... 'TB': 'https://topbicycle.ru' ... }
The result is a dictionary of four "key: value" pairs
>>> urls['Stels']
Numbers can also be used as keys
def Test(): numbers = { 0: "Zero", 1: "One" } o = numbers[0] print(o) if __name__ == "__main__": Test()
Zero
Turn into a dictionary
With the function dict() you can turn a list of tuples into a dictionary
names_and_ages = [('Alice', 32), ('Bob', 48), ('Charlie', 28), ('Daniel', 33)] d = dict(names_and_ages) print(d)
{'Alice': 32, 'Bob': 48, 'Charlie': 28, 'Daniel': 33}
Or comma-separated key-value arguments
phonetic = dict(a="alfa", b="bravo", c="charlie", d="delta", e="echo", f="foxtrot") print(phonetic)
{'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'e': 'echo', 'f': 'foxtrot'}
Copying dictionaries, like copying lists, is a shallow copy that is, it is not the objects that are copied but references to them. You can see the difference in detail here
# copy dict d = dict(it="urn.su", bikes="topbicycle.ru", travel="heihei.ru") e = d.copy() print(e) f = dict(e) print(f) # Next method will not create a copy # g will be the same object g = e print(g) print(e is d) print(e == d) print(f is e) print(f == e) print(g is e) print(g == e) # Let's prove g is not a copy d["it"] = "eth1.ru" print('d["it"] = "eth1.ru"') print('d["it"] = "eth1.ru"') print("d: ", d) print("e: ", e) print("f: ", f) print("g: ", g) e["it"] = "devhops.ru" print('e["it"] = "devhops.ru"') print("e: ", e) print("f: ", f) print("g: ", g)
{'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} False True False True True True d["it"] = "eth1.ru" d: {'it': 'eth1.ru', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} e: {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} f: {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} g: {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} e["it"] = "devhops.ru" e: {'it': 'devhops.ru', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} f: {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} g: {'it': 'devhops.ru', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'}
Update: add one dictionary to another
# update d = dict(it="urn.su", bikes="topbicycle.ru", travel="heihei.ru") e = dict(hotels="booking.com", flights="aviasales.ru", trains="tutu.ru") print("d: ", d) print("e: ", e) e.update(g) print("e.update(g)") print("e: ", e)
d: {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'} e: {'hotels': 'booking.com', 'flights': 'aviasales.ru', 'trains': 'tutu.ru'} e.update(g) e: {'hotels': 'booking.com', 'flights': 'aviasales.ru', 'trains': 'tutu.ru', 'it': 'devhops.ru', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'}
With update() you can not only add new values but also change old ones.
print('d.update(it="eth1.ru")') print("d: ", d)
d.update(it="eth1.ru") d: {'it': 'eth1.ru', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru'}
Iteration: looping over dictionary items
# iteration sites = dict( it="urn.su", bikes="topbicycle.ru", travel="heihei.ru", hotels="booking.com", flights="aviasales.ru", trains="tutu.ru" ) for key in sites: print(f"{key} => {sites[key]}")
it => urn.su bikes => topbicycle.ru travel => heihei.ru hotels => booking.com flights => aviasales.ru trains => tutu.ru
print("\nkeys:\n") for key in sites: print(key) for key in sites.keys(): print(key) print("\nvalues:\n") for value in sites.values(): print(value)
keys: it bikes travel hotels flights trains it bikes travel hotels flights trains values: urn.su topbicycle.ru heihei.ru booking.com aviasales.ru tutu.ru
Items: looping over key-value tuples
With items() you can loop over key-value pairs; a tuple is returned
# items print("\nitems:\n") for key, value in sites.items(): print(f"{key} => {value}")
items: it => urn.su bikes => topbicycle.ru travel => heihei.ru hotels => booking.com flights => aviasales.ru trains => tutu.ru
in, not in, del
# in and not in print("in and not in\n") sites = dict( it="urn.su", bikes="topbicycle.ru", travel="heihei.ru", hotels="booking.com", flights="aviasales.ru", trains="tutu.ru" ) print("it" in sites) # True print("urn.su" in sites) # False since urn.su is not a key print("velodrive" not in sites) # True # del del sites["hotels"] print('del sites["hotels"]') print(sites)
in and not in True False True del sites["hotels"] {'it': 'urn.su', 'bikes': 'topbicycle.ru', 'travel': 'heihei.ru', 'flights': 'aviasales.ru', 'trains': 'tutu.ru'}
Modifying values inside a dictionary
m = { 'H': [1, 2, 3], 'He': [3, 4], 'Li': [6, 7], 'Be': [7, 9, 10], 'B': [10, 11], 'C': [11, 12, 13, 14] } print(m) m['H'] += [4, 5, 6, 7] print(m) m['N'] = [13, 14, 15]
{'H': [1, 2, 3], 'He': [3, 4], 'Li': [6, 7], 'Be': [7, 9, 10], 'B': [10, 11], 'C': [11, 12, 13, 14]} {'H': [1, 2, 3, 4, 5, 6, 7], 'He': [3, 4], 'Li': [6, 7], 'Be': [7, 9, 10], 'B': [10, 11], 'C': [11, 12, 13, 14]} {'B': [10, 11], 'Be': [7, 9, 10], 'C': [11, 12, 13, 14],
pprint: readable output
With pprint() you can print a dictionary to the screen in a readable form
from pprint import pprint as pp m = { 'H': [1, 2, 3], 'He': [3, 4], 'Li': [6, 7], 'Be': [7, 9, 10], 'B': [10, 11], 'C': [11, 12, 13, 14] 'N': [13, 14, 15] } pp(m)
'H': [1, 2, 3, 4, 5, 6, 7], 'He': [3, 4], 'Li': [6, 7], 'N': [13, 14, 15]}
get()
With the get() method you can get a value by key.
Syntax
Dict.get(key, default=None)
Parameters:
key: the name of the key whose value you want to get
Value: (Optional) the value to return if the key is not found. By default it returns None.
Example: consider a dictionary where the keys are the names of cities in Andalusia
(Spain), and the value is their population in thousands of people
Let us apply get() with only one argument, then with two for a city from the list and a city not from the list
cities = {"Benalmadena": 67, "Cordoba": 325, "Fuengirola": 75, "Malaga": 569, "Torremolinos": 68} print(cities.get("Cordoba")) print(cities.get("Malaga", "Unknown")) print(cities.get("Riga", "Unknown"))
325 569 Unknown
Riga is a city in Latvia and not in Spain, so get() returned Unknonw
Article author: Andrei Olegovich