17.2. Nested DictionariesΒΆ
Just as lists can contain items of any type, the value associated with a key in a dictionary can also be an object of any type. In particular, it is often useful to have a list or a dictionary as a value in a dictionary. And of course, those lists or dictionaries can also contain lists and dictionaries. There can be many layers of nesting.
Only the values in dictionaries can be objects of arbitrary type. The keys in dictionaries must be one of the immutable data types (numbers, strings, tuples).
Check Your Understanding
- d[5] = {1: 2, 3: 4}
- 5 is a valid key; {1:2, 3:4} is a dictionary with two keys, and is a valid value to associate with key 5.
- d[{1:2, 3:4}] = 5
- Dictionary keys must be of immutable types. A dictionary can't be used as a key in a dictionary.
- d['key1']['d'] = d['key2']
- d['key2'] is {'b': 3, 'c': "yes"}, a python object. It can be bound to the key 'd' in a dictionary {'a': 5, 'c': 90, 5: 50}
- d[key2] = 3
- key2 is an unbound variable here. d['key2'] would be OK.
Which of the following is a legal assignment statement, after the following code executes?
d = {'key1': {'a': 5, 'c': 90, 5: 50}, 'key2':{'b': 3, 'c': "yes"}}
1. Extract the value associated with the key color and assign it to the variable color
. Do not hard code this.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.