Python 2.7 – Fundamentals – Collections – Dictionaries

Just like a set, a dictionary is an unordered collection. A dictionary represents a collection of key:value pairs. In other words, we can use a data type to reference an item instead of just the index of the item. These key:value pairs are separated by commas. Dictionaries are declared in curly brackets. Each item can be a collection item also. Some examples are given below:

 

 

 

 

 

 

In dict2 above, note that we used the key of “3” as a string instead of a number. dict3 shows how a dictionary can store collection objects.

Operators

The following operators work on dictionaries:

  • [] – index operator
  • in – search operator
  • del – delete operator
  • len – length operator. It is more a function than an operator

[] – indexing operator

This is used to get the value of a key that exists in the dictionary. If the key does not exist then an error is thrown.

in – search operator

The in operator returns true if a key exists in the dictionary else false

del – delete dict[key]

This deletes a key:value pair from the dictionary. If the key does not exist, an error is thrown

len – len(dict)

This returns the count of items in the dictionary. If there are no items then a length of zero is returned.

 

 

 

 

 

Methods

The following methods are available for dictionaries:

  • keys – Returns all the keys in the dictionary
  • values – Returns all the values in the dictionary
  • items – Returns all the key:value pairs
  • get – get the value of a key)

keys – dict.keys()

Returns all the keys in the dictionary as a list.

values – dict.values()

Returns all the values int the dictionary as a list

items – dict.items()

Returns all the key:value pairs as a list. Each pair is a list within the main list

get – dict.get(key, alternative)

Gets the value of a key. If a key is not found and alternative is not specified then it returns None. If alternative is specified then it returns the alternative value.

 

 

 

 

 

 

 

 

 

 

In the items method you can see that the pairs are returned as a list with each pair item returned as a list. So usingĀ  list indexing we can refer to the first pair as list[0] and then the first item within the first pair as list[0][1]

 

In the next post we will look at Basic Input and Output

 

1 Trackback / Pingback

  1. Python 2.7 – Fundamentals – Collections – Sets – Truelogic Blog

Leave a Reply

Your email address will not be published.


*