1

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?

Christopher Markieta
5,99110 gold badges49 silver badges64 bronze badges
asked Jan 18, 2012 at 5:29
4
  • 1
    +1 for an innovative use of basic tag. Commented Jan 18, 2012 at 5:33
  • 1
    Welcome to SO! Please include some code with your posts of what you have tried and the errors you encountered so we can help. You'll get much better answers. Commented Jan 18, 2012 at 5:34
  • nested dicts (or other objects) are accessible. You can probably figure it out if you play with it on the command line. Good Luck! Commented Jan 18, 2012 at 5:40
  • What have you tried? Show the code where you create the nested data structure, the code where you try to access something, what you expect to access, and what happens instead. Commented Jan 18, 2012 at 6:56

4 Answers 4

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'
answered Jan 18, 2012 at 5:38
Sign up to request clarification or add additional context in comments.

3 Comments

Fastest, most amazing answer ever. This is beyond perfect, its an education. Thanks so much.
Technically, dictionary keys have to be hashable, not immutable. For example, if you subclass list and add __hash__ method, you will be able to use its instances as dict keys.
@billbixby: Welcome to StackOverflow. "Thanks so much" is best expressed "by clicking on the check box outline to the left of the answer".
2

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']

answered Jan 18, 2012 at 5:38

Comments

1

To touch on a few things:

  1. Adding a dict to a list.

    mylist = []

    mylist.append({'key1': 'val1'})

  2. Adding a list to a set.

    myset = set()

    myset.add({'key1': 'val1'}) # Error - dicts are mutable, therefore not hashable.

  3. Keeping track of distinct dictionaries.

    mydicts = set([id(d) for d in mylist])

  4. Retrieving elements.

    # With Lists

    mylist[0]['key1']

    # With Sets

    mydicts[0] # Error - sets do not support indexing.

answered Jan 18, 2012 at 5:41

Comments

0
x = [{"a":1},{"b":2}]
>>> x[1]["b"]
2
answered Jan 18, 2012 at 5:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.