Dicts Flashcards

1
Q

What are dictionaries in Python?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to return value from dict by given key?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What happens when you call d[“key_name”] and such key doesn’t exist?

A

KeyError: ‘key_name’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which datatypes are allowed to be dict’s keys?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Name 6 ways of dict declaration.

A
  1. dict literal {key: value} or dict comprehension in {}
  2. dict()
  3. dict(**kwargs)
  4. dict(mapping, **kwargs)
  5. dict(iterable, **kwargs)
  6. dict.fromkeys(iterable, )

Literals are the fastest way.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to create dict with it’s literals?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What if positional arguments or kwargs aren’t given to dict() ?

A

An empty dictionary is created.
»> d = dict(); print d
{}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How keyword args in dict(**kwargs) can be used?

A

> > > 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to use dict(mapping)?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to use dict(iterable)?

A

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’}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What if you provide kwargs alongside mapping or iterable like in dict([(‘a’, 1)], a=2)?

A

{‘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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to assign new item (key and value) to existing dict?

A

> > > 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to change / update existing key in dict?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What if I want dict to be ordered?

A

use collections.OrderedDict which remembers insertion order:
from collections import OrderedDict
help(OrderedDict)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

d={}
d[‘key’] = 1
d[‘Key’] = 2

Are keys case-sensitive?

A

Yes, they’re!

> > > print d
{‘Key’: 2, ‘key’: 1}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which datatypes are allowed to be dict’s values?

A

Dict values can be any datatype.

17
Q

How to delete item from the dict by given key?

A

> > > del d[‘Key’] # doesn’t return nothing on success, else - KeyError
or
d.pop(key, “default_value”) # a. if key exists - remove it and b. return it; c. no such key? - keyerror or default value when provided.

18
Q

How to clear the whole dict to empty {} condition?

A

d.clear()

19
Q

How to get dict’s items as iterable value?

A

> > > d.items() # list of tuples like [(‘Key’, 2), (‘key’, 1)]
# or
d.iteritems() iterable generator obj to iterate through it, looks almost the same as the list above, but saves typical generator objects behavior

20
Q

How to get list of all dict’s keys?

A

> > > d.keys() # list of keys like [‘Key’, ‘key’]
d.iterkeys() # generator obj
iter(d) # almost the same generator obj, but iter(d) == d.iterkeys() comparison gives False

21
Q

How to get list of all dict’s values?

A

> > > d.values() # list of values like [2, 1]

|&raquo_space;> d.itervalues() # generator obj

22
Q

What can you use to get length of dictionary?

A

built-in len method:

|&raquo_space;> len(d) # returns number of items

23
Q

Is it possible to add custom behavior on KeyError key absence?

A

Yeah, two ways:

  1. Use d.get(‘key’, ‘optional default value to return if no such key’)
  2. overwrite it with __missing__ method for your custom dict class:
>>> class Counter(dict):
...     def \_\_missing\_\_(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
24
Q

How to check for existence / absence of key in the dictionary?

A

> > > key in d # returns True/False if key is in d.keys()
key not in d
d.has_key(key) # BUT it is outdated, use statements above.

25
Q

How to copy dict to new one?

A

> > > new_d = d.copy() # shallow copy, but doesn’t work for nested complicated objects in values places. If you want deep copy - use import copy; help(copy.deepcopy) otherwise.

26
Q

How works dict.fromkeys method?

A

dict.fromkeys(sequence, value=None)
builds new dictionary with keys from iterable object and optional_default_value for them.

> > > dict.fromkeys(‘hello’, ‘default value’)
{‘h’: ‘default value’, ‘e’: ‘default value’, ‘l’: ‘default value’, ‘o’: ‘default value’}
d = dict.fromkeys([1,2], ‘default value’)
{1: ‘default value’, 2: ‘default value’}
dict.fromkeys(d.iterkeys(), ‘default value’)
{1: ‘default value’, 2: ‘default value’}

Keep in mind that duplicated or more keys gonna be overwritten.

27
Q

How to remove arbitrary item from dict?

A

d.popitem()

28
Q

What is item in dictionary?

A

Single one-to-one relationship of key: value.

29
Q

How to merge two dicts?

A

base_dict.update(other_dict) # update base_dict with contents of other_dict including rewrite for existing values. other_dict has higher precedence.

>>> base_dict = {"a": 1}
>>> other_dict = {"a": 2, "b": 2}
>>> base_dict.update(other_dict)
>>> base_dict
{'a': 2, 'b': 2}
30
Q

What are dict views?

A

The objects returned by d.viewkeys(), d.viewvalues() and d.viewitems() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data, and support membership tests.

31
Q

What are membership tests on dict views?

A

Membership tests are set-like checks on membership, intersection and differences between two dict views or two dict viewkeys:

> > > dictview & other
Return the intersection of the dictview and the other object as a new set.
dictview | other
Return the union of the dictview and the other object as a new set.
dictview - other
Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set.
dictview ^ other
Return the symmetric difference (all elements either in dictview or other, but not in both) of the dictview and the other object as a new set.

32
Q

Is it possible to use trailing comma after last item pair in the dict?

A

Sure, also put a space between the trailing comma and the closing brace (acc. PEP8):

> > > role = {“By day”: “A typical programmer”,
“By night”: “Still a typical programmer”, }

33
Q

What is shallow copy?

A

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

import copy
copy.copy(x) # return shallow copy of x
# or 
your_dict.copy() # return shallow copy of your_dict
34
Q

What is deep copy?

A

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

import copy
copy.deepcopy(x) # return deepcopy of x