Dicts Flashcards
What are dictionaries in Python?
Dictionary is an unordered collection of one-to-one relationships between keys and values
»> my_dict = {“key”: “value”, “name”: “nick”}
Unordered means that keys order may change if you call my_dict few times.
How to return value from dict by given key?
d[key_name], e.g.:
»> my_dict[“name”]
“nick”
or d.get(key_name), but this approach doesn’t throw KeyError on key_name non-existence.
What happens when you call d[“key_name”] and such key doesn’t exist?
KeyError: ‘key_name’
Which datatypes are allowed to be dict’s keys?
Values that are not hashable - strings, integers, tuples. Floats can be too, but their values can be approximated and floored that’s why avoid their usage as keys.
Name 6 ways of dict declaration.
- dict literal {key: value} or dict comprehension in {}
- dict()
- dict(**kwargs)
- dict(mapping, **kwargs)
- dict(iterable, **kwargs)
- dict.fromkeys(iterable, )
Literals are the fastest way.
How to create dict with it’s literals?
Use {key: value} or dict comprehension in {}
»> a = {“one”: 1, “two”: 2, “three”: 3} # dict literal {key:value}
»> b = {key: value for key, value in [(“one”, 1), (“two”, 2), (“three’” 3)]} # comprehension
»> a == b # True
What if positional arguments or kwargs aren’t given to dict() ?
An empty dictionary is created.
»> d = dict(); print d
{}
How keyword args in dict(**kwargs) can be used?
> > > b = dict(one=1, two=2, three=3)
But keep in mind that keyword names can’t be used as an expression:
»> dict(1=”a”)
SyntaxError: keyword can’t be an expression
»> dict(“1”=”a”)
SyntaxError: keyword can’t be an expression
»> dict(a=”a”)
{a: “a”}
How to use dict(mapping)?
A mapping is a collection of key/value pairs that allow key access to value - it “maps” keys to values. The most obvious mapping builtin type is the dict. Or you can use list of tuples of pairs:
»> d = dict([(‘two’, 2), (‘one’, 1), (‘three’, 3)])
{‘three’: 3, ‘two’: 2, ‘one’: 1}
How to use dict(iterable)?
An iterable is an object that can be iterated - which basically means you can use it in a for obj in iterable: statement. This include sequence types (strings, lists, etc) as well as quite a few other (files, dbapi cursors, generators etc), and, well, dicts too.
Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
»>dict([‘ab’, ‘cd’, ‘ef’])
{‘a’: ‘b’, ‘c’: ‘d’, ‘e’: ‘f’}
What if you provide kwargs alongside mapping or iterable like in dict([(‘a’, 1)], a=2)?
{‘a’: 2}
If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
How to assign new item (key and value) to existing dict?
> > > d[‘new_key’] = ‘value’
or
d.setdefault(‘new_key’, ‘value’) # if key doesn’t exist - create it with default value None or value; if exists - do nothing.
How to change / update existing key in dict?
Just rewrite it as d[‘old_key’] = ‘some new value’
You cannot have duplicate keys in the dict, assigning a value to an existing key will wipe out the old value.
What if I want dict to be ordered?
use collections.OrderedDict which remembers insertion order:
from collections import OrderedDict
help(OrderedDict)
d={}
d[‘key’] = 1
d[‘Key’] = 2
Are keys case-sensitive?
Yes, they’re!
> > > print d
{‘Key’: 2, ‘key’: 1}