Uploaded by Mr C

Python NestedList

advertisement
DICTIONARY IN NESTED LIST
nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50},
{'b': 3, 'c': "yes"}]
#write code to print the value associated with key
'c' in the second dictionary (90)
def square(x):
return x*x
L = [square, abs, lambda x: x+1]
print(nested2[1]['c'])
#write code to print the value associated with key
'b' in the third dictionary
print(nested2[2]['b'])
#add a fourth dictionary add the end of the list;
print something to check your work.
nested2.append({'boy':212})
print(nested2)
print("****names****")
for f in L:
print(f)
print("****call each of them****")
for f in L:
print(f(-2))
#change the value associated with 'c' in the third
dictionary from "yes" to "no"; print something to
check your work
print("****just the first one in the list****")
nested2[1]['c'] = 'yes'
print(L[0](3))
print(L[0])
print(nested2)
OUTPUT
OUTPUT
90
****names****
3
[{'a': 1, 'b': 3}, {5: 50, 'a': 5, 'c':
90}, {'b': 3, 'c': 'yes'}, {'boy': 212}]
[{'a': 1, 'b': 3}, {5: 50, 'a': 5, 'c':
'yes'}, {'b': 3, 'c': 'yes'}, {'boy':
212}]
<function square>
<built-in function abs>
<function <lambda>>
****call each of them****
4
2
-1
****just the first one in the list****
<function square>
9
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.
Extract the value associated with the key color and assign it
to the variable color. Do not hard code this.
info = {'personal_data':
{'name': 'Lauren',
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).
'age': 20,
'major': 'Information Science',
'physical_features':
{'color': {'eye': 'blue',
Check Your Understanding
'hair': 'brown'},
nested-2-1: 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"}}
A. d[5] = {1: 2, 3: 4}
'height': "5'8"}
},
'other':
{'favorite_colors': ['purple', 'green', 'blue'],
'interested_in': ['social media', 'intellectual property',
'copyright', 'music', 'books']
}
B. d[{1:2, 3:4}] = 5
C. d['key1']['d'] = d['key2']
D. d[key2] = 3
✔️Correct.
A. 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.
C. 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}
}
#ANSWER
color = info['personal_data']['physical_features']
['color']
print(color)
OUTPUT
{'eye': 'blue', 'hair': 'brown'}
JSON stands for JavaScript Object Notation. It
looks a lot like the representation of nested
dictionaries and lists in python when we write
them out as literals in a program, but with a few
small differences (e.g., the word null instead of
None). When your program receives a JSONformatted string, generally you will want to
convert it into a python object, a list or a
dictionary.
Again, python provides a module for doing this.
The module is called json. We will be using two
functions in this module, loads and dumps.
json.loads() takes a string as input and produces a
python object (a dictionary or a list) as output.
Consider, for example, some data that we might
get from Apple’s iTunes, in the JSON format:
import json
a_string = '\n\n\n{\n "resultCount":25,\
n "results": [\n{"wrapperType":"track",
"kind":"podcast",
"collectionId":10892}]}'
['resultCount', 'results']
25
The other function we will use is dumps. It does the
inverse of loads. It takes a python object, typically a
dictionary or a list, and returns a string, in JSON
format. It has a few other parameters. Two useful
parameters are sort_keys and indent. When the value
True is passed for the sort_keys parameter, the keys of
dictionaries are output in alphabetic order with their
values. The indent parameter expects an integer.
When it is provided, dumps generates a string
suitable for displaying to people, with newlines and
indentation for nested lists or dictionaries. For
example, the following function uses json.dumps to
make a human-readable printout of a nested data
structure.
import json
def pretty(obj):
return json.dumps(obj, sort_keys=True,
indent=2)
d = {'key1': {'c': True, 'a': 90, '5': 50},
'key2':{'b': 3, 'c': "yes"}}
print(d)
print(a_string)
print('--------')
d = json.loads(a_string)
print(pretty(d))
print("------")
print(type(d))
OUTPUT
print(d.keys())
{'key1': {'c': True, 'a': 90, '5': 50}, 'key2': {'c': 'yes',
'b': 3}}
print(d['resultCount'])
# print(a_string['resultCount'])
OUTPUT
{
"resultCount":25,
"results": [
{"wrapperType":"track",
"kind":"podcast",
"collectionId":10892}]}
-----<class 'dict'>
-------{"key1":{"5":50,"a":90,"c":true},"key2":
{"b":3,"c":"yes"}}
Download