Just getting started with python, trying to nest a dict inside other data structures, lists, sets, etc. When I nest the dict (like, if I create a list of dicts), I cant seem to reference the keys or values inside the individual dicts anymore. Is this a design feature or am I totally boning it?
4 Answers 4
You can absolutely do this with Python. You can use the [] operator more than once -- if a is a list, then a[0] is its first element. If that first element happens to be a dict, then you can see its keys with a[0].keys(), and you can get the values out of it like this: a[0]["here's a key"]
And just like you would loop over the keys of a dictionary like this:
for key in my_dict:
# get the value
val = my_dict[key]
# do something with it
You can use an element of a list, if it happens to be a dict:
for key in a[0]:
# get the value
val = a[0][key]
# do something with it
You can make lists of lists, lists of dicts, or even dicts where the values are lists (or more dicts), pretty easily. And to reference into them, you can either iterate over their values, or chain [] operations as needed.
About the only thing that you can't do is to use lists or dicts as keys to another dict. One of the rules is that dictionary keys have to be immutable. Numbers are OK, strings are OK, tuples are OK, but lists and dicts are not.
Here's a sample of interactive code, to show you how to build up lists of dicts, and extract their values again:
# Here's a dictionary
a = { 'key1': 'value1', 'key2': 2 }
# Check it out
>>> type(a)
<type 'dict'>
# Print it:
>>> a
{'key1': 'value1', 'key2': 2}
# Look inside
>>> a['key1']
'value1'
# Here's another one
b = { 'abc': 123, 'def': 456 }
# Now let's make a list of them
c = [a, b]
# Check that out, too
>>> type(c)
<type 'list'>
# Print it:
>>> c
[{'key1': 'value1', 'key2': 2}, {'def': 456, 'abc': 123}]
>>> c[0]
{'key1': 'value1', 'key2': 2}
# Dig deeper
>>> c[0]['key1']
'value1'
3 Comments
list and add __hash__ method, you will be able to use its instances as dict keys.When you have nested dicts (or nested anything for that matter), you have to provide the index of the desired dict in the outside list, and then the index of the desired item. So, if you had a couple dicts in a list:
list_of_dicts = [{'a':1,'b':2,'c':3},{'d':4,'e':5,'f':6}]
to access element 'e' of the second dict, you would enter: list_of_dicts[1]['e']
Comments
To touch on a few things:
Adding a dict to a list.
mylist = []mylist.append({'key1': 'val1'})Adding a list to a set.
myset = set()myset.add({'key1': 'val1'}) # Error - dicts are mutable, therefore not hashable.Keeping track of distinct dictionaries.
mydicts = set([id(d) for d in mylist])Retrieving elements.
# With Listsmylist[0]['key1']# With Setsmydicts[0] # Error - sets do not support indexing.
Comments
x = [{"a":1},{"b":2}]
>>> x[1]["b"]
2
basictag.