One of the fist things you’ll most likely encounter with Python are the datatypes lists and dicts. While they initially seem quite simple, things can get awfully complex, awfully fast when you start intermingling the two datatypes. So we’ll start with the basics, then dive into some more complex examples.
Lists
Lists are defined as ‘a collection of different pieces of information as a sequence under a single variable name’. So that’s a fancy way of saying it’s just a list. In Python, lists are defined by using the ‘[]’ brackets. So for example…
# A list with one item list = ["Jon"] # A list with multiple items list = ["Jon", "Matt", "Bill"] # An empty list list = []
Items in lists can be accessed by index. For example…
# A list with multiple items list = ["Jon", "Matt", "Bill"] print "The second name in the list is " + list[1] # Result The second name in the list is Matt
We can also iterate through the list with a simple loop…
# A list with multiple items list = ["Jon", "Matt", "Bill"] for name in list: print name # Result Jon Matt Bill
Lists can be added to by using the list attribute ‘append’. For instance…
# A list with multiple items list = ["Jon", "Matt", "Bill"] list.append("Bob") print len(list) # Result 4
Additionally, lists can contain items of multiple different types…
# A list with multiple types of items list = [1, “Jon”] type(list[0]) # Result int type(list[1]) # Result str
Dicts
Dicts are more of a ‘key/value’ kind of arrangement. Like lists, they are mutable, and can be initialized with data or empty. The major difference in definition is that dicts use ‘{}’ whereas lists used ‘[]’. For example…
# Any empty dict dict = {} #Add a couple of key-value pairs dict['Jon'] = "Langemak" dict['Matt'] = 30 print dict['Jon'] print dict['Matt'] # Result Langemak 30
You might have noticed that we’re just printing the values. If you need to print the key, you can do so as well but that doesn’t need to be returned from the dict since you’re using it to find the value. So you can either just print it, or you can iterate through the items in the dict using a for loop and return both the key and the value…
# Define the dict dict = {'Jon' : 'Langemak', 'Matt' : 30} print "Key:Jon - Value:" + dict['Jon'] for key,value in dict.iteritems(): print key,value # Result 1 Key:Jon - Value:Langemak # Result 2 Matt 30 Jon Langemak
Getting more complicated
Note that above the dict is holding different kinds of value. ‘Langemak’ was type string and ‘30’ was type integer. This means that dicts can hold a variety of different datatypes including lists! Let’s take a quick example so you can see what I mean…
# Create a dict containing multiple types dictoflists = {'Fruit' : ['Apple','Pear','Orange'], 'Jon' : 'Langemak', 'Cars' : ['Jeep','BMW']} # For loop to print the values depending on value type for key, value in dictoflists.iteritems(): if type(value) is list: for listitems in value: print listitems if type(value) is str: print value # Result Jeep BMW Apple Pear Orange Langemak
Conversely, lists can hold a variety of datatypes such as dicts…
# Create a list containing multiple types listofdicts = [{'Fruit' : 'Apple'},'Jon',{'Cars' : 'Jeep'}] for listitems in listofdicts: if type(listitems) is str: print listitems if type(listitems) is dict: for key, value in listitems.iteritems(): print key, value # Result Fruit Apple Jon Cars Jeep
So you can see that I can store multiple types of data in a dictionary. When we print the data out our for loop needs to check and see what type of data the value matching the key holds. For the values that are lists we execute an additional loop to run through the entire list. So this is pretty easy to understand, but take a look at this example that I came across when I experimenting with a network switch API…
Interestingly enough, Python sees the ‘[‘ and interprets that this is a list. Lists are delineated by commas and defined within brackets. So if we look at this, we can see that what we really have is a one list, with one item in it. What’s more interesting is that the lists single item is a dict. We can see this by using the following code…
list=[ { "vrfs": { "test": { "asn": 200, "peers": { "1.1.1.1": { "asn": 6500, "inMsgQueue": 0, "msgReceived": 0, "msgSent": 0, "outMsgQueue": 0, "peerState": "Idle", "peerStateIdleReason": "NoInterface", "prefixAccepted": 0, "prefixReceived": 0, "upDownTime": 1442951806.24449, "version": 4 }, "2.2.2.2": { "asn": 6501, "inMsgQueue": 0, "msgReceived": 0, "msgSent": 0, "outMsgQueue": 0, "peerState": "Idle", "peerStateIdleReason": "NoInterface", "prefixAccepted": 0, "prefixReceived": 0, "upDownTime": 1442951825.246168, "version": 4 }, "3.3.3.3": { "asn": 6502, "inMsgQueue": 0, "msgReceived": 0, "msgSent": 0, "outMsgQueue": 0, "peerState": "Idle", "peerStateIdleReason": "NoInterface", "prefixAccepted": 0, "prefixReceived": 0, "upDownTime": 1442951832.247766, "version": 4 } }, "routerId": "10.11.160.114", "vrf": "test" } } } ] # Show that the main type is a list print type(list) # Show that the lists item is a dict print type(list[0]) # Result type 'list' type 'dict'
We can see that Python sees the lists one object as a dict. What’s more interesting is that what we really have is a bunch of nested dicts…
So in this example, the first dict has a key of ‘vrfs’ and a value of ‘test’ which happens to be another dict. The dict ‘test’ has 4 key/value pairs with keys ‘asn’, ‘peers’, ‘routerId’, and ‘vrf’. Then from there each peer value is also a dict which contain more key/value pairs describing the given peer. We can get an idea of how you access each of the dicts by looking at this example which returns how many keys are in each nested dict…
# Number of keys in the first dict print len(list[0]['vrfs']) # Number of keys in the second dict print len(list[0]['vrfs']['test']) # Number of keys in the third dict print len(list[0]['vrfs']['test']['peers']) # Number of keys in one of the peer dicts print len(list[0]['vrfs']['test']['peers']['1.1.1.1']) # Result 1 4 3 11
So as you can see, you lists and dicts in Python can be pretty flexible. Next up, more Python!
When you start experimenting with pulling data from that API you may want to take a look at the python ‘json’ library. It will let you take JSON data and natively manipulate it with dict tools then convert it back to JSON.
Nice! Thanks for the tip!
Good article but i would suggest not to use reserved words for variable names (list) and also try to teach the pythonic style of naming things listofdicts vs list_of_dicts etc.
http://legacy.python.org/dev/peps/pep-0008