TAGS: |

How To Reference Nested Python Lists & Dictionaries

Ethan Banks

This post originally appeared in the Packet Pushers’ Ignition site on March 10, 2020.

When getting data back from API queries in Python, the data is often delivered in JSON format. Python libraries such as requests will convert that JSON data structure into a Python-native data structure you can work with. That Python data structure is probably going to be a dictionary, list, or nested combination of the two.

The trick is referencing the data element you need to work with. This is straightforward once you’re used to it, but befuddling if you’re not. We’ll walk through lists, dictionaries, and nested combinations of the two using a series of examples.

Python Lists

A Python list is a series of objects referenced numerically by position. Lists are delimited by square brackets. List items are separated by commas.

colorsList = ['red', 'green', 'blue']
  • colorsList[0] = ‘red’
  • colorsList[1] = ‘green’
  • colorsList[2] = ‘blue’

Python Dictionaries

A Python dictionary (aka dict) is a series of key-value pairs referenced by key name. Dicts are delimited by curly braces. Key-value pairs are separated by commas. A key is separated from its value by a colon.

In this example, I split the key-value pairs across lines for readability. This is valid Python syntax as written below, but the dict could have also been written as one long line. Don’t do that, though. Use PEP8 guidelines and check your code for PEP8 compliance here.

  • colorsDict[‘red’] = ‘Red Tide Metallic’
  • colorsDict[‘green’] = ‘Leafing Out Green’
  • colorsDict[‘blue’] = ‘Deep Berry Blue’

Python List Containing Dicts

A Python list can contain a dictionary as a list item. Here’s a list containing a mix of string objects and dictionaries.

  • colorsList[0]=’red’
  • colorsList[1]={‘2020’: ‘Red Gloss’, ‘2019’: ‘Rust Matte’, ‘2018’: ‘Ruby Flake’}
  • Etc…

Huh. If colorsList[1] is equal to the entire dict, how do we get at the individual values in the dict? By adding an additional reference value.

  • colorsList[1][‘2020’] = ‘Red Gloss’
  • colorsList[1][‘2019’] = ‘Rust Matte’
  • colorsList[1][‘2018’] = ‘Ruby Flake’

Not so bad, right? Make sense? Good. Let’s look at one more example.

Python Dict Containing Lists

A Python dictionary can contain a list as the value portion of a key-value pair entry. Here’s a dict that does exactly that.

  • colorsDict[‘2020’] = [‘Red Gloss’, ‘Leafy Gloss’, ‘Berry Gloss’]
  • Etc…

Hmm. If colorsDict[‘2020’] equals an entire list, how do we get at individual elements in the list? By adding an additional reference value.

  • colorsDict[‘2020’][0] = ‘Red Gloss’
  • colorsDict[‘2020’][1] = ‘Leafy Gloss’
  • colorsDict[‘2020’][2] = ‘Berry Gloss’

Will Python Allow For More Deeply Nested Data Structures?

Yes, Python will allow for more deeply nested data structures than I’ve shown you here. Simply add additional references to get down to the individual element you need to work with. One API I was recently working with returned a JSON object that the requests library converted into a dictionary containing a list containing more dictionaries. Wheeeee….

Your Python code isn’t likely to contain many clunky references like colorsList[1][‘2018’] to get to the thing you need. You’ll be looping through a list. Or you’ll assign the thing you need to a variable so that you only need to be clunky once.

Even so, understanding how to reference the data element you need is fundamental to maintaining your sanity when working in Python. If you’re using Python for network automation, you’ll likely be using nested dicts and lists constantly. Stay sane out there.

Try It!

Invoke the Python interpreter, and start working with lists, dicts, and nested variations. Keep doing it until the answers you’re getting back from the interpreter are what you expect. Make sure you try things that you think shouldn’t work so that you understand the errors the Python interpreter will give back.

Here’s some output from a session I had with the Python interprester playing with a dict containing a nested list.

Have fun!

About Ethan Banks: Hey, I'm Ethan, co-founder of Packet Pushers. I spent 20+ years as a sysadmin, network engineer, security dude, and certification hoarder. I've cut myself on cage nuts. I've gotten the call at 2am to fix the busted blinky thing. I've sat on a milk crate configuring the new shiny, a perf tile blowing frost up my backside. These days, I research new enterprise tech & talk to the people who are making or using it for your education & amusement. Hear me on the Heavy Networking podcast.