Dictionaries

Introduction to Dictionaries

Dictionaries in Python are unordered collections of key: value pairs. They are similar in that regard to JavaScript Objects and they follow the syntax of:

  • Being enclosed by (starting and ending with) curly brackets: {}
  • A dictionary is defined by assigning a variable to the curly brackets
  • Each key:value pair is separated by a comma: ,
  • They key can be either a string or a number
  • Values can be any data type
  • New keys and corresponding values can be added to an existing dictionary by using the .update method and passing a dictionary of the new key:value pairs as the argument
# Creating an empty dictionary
empty_dictionary = {}

# Creating a simple dictionary
simple_dictionary = {
	'name': 'Adam',
	'occupation: 'Engineer',
	'age': 34,
}

# Adding a new key and value
simple_dictionary.update({'location':'Europe'})

Accessing Values in a Dictionary

You can access values in a dictionary by the following syntax: dictionary[key]. This can be used to overwrite the existing key values of a dictionary by assigning it a new value. However if the key is not found it will return a KeyError. In order to avoid this you can use the .get method and define a default value to be returned in this case.

# Return the value of the passed key
simple_dictionary['occupation']
#Overwriting an existing key value
simple_dictionary['occupation'] = 'Software Engineer'
# Return the key or a default value e.g. 'Key not found'
simple_dictionary.get(key, 'Key not found')

You can also return aspects of the dictionary as iterables using the following methods:

  • list(dictionary): Shows all keys as a list
  • dictionary.keys(): Returns a dict_keys object
  • dictionary.values(): Returns a dict_values object
  • dictionary.items(): Returns a dict_list object as tuples of key, value

Combining Lists into Dictionaries

You can think of a dictionary as two connected lists, one for the keys and the other for the values and as such you can actually combine two lists into a dictionary with the following syntax.

# Combining lists into a dictionary
joint_dictionary = {key:value for key, value in zip(list1, list2)}
  • This takes lists 1 and 2 and 'zips' them together in a dictionary.
  • It puts list1 as the keys.
  • It puts list2 as the values.
  • This is the general syntax, but the 'for key, value' uses temporary variables, so to be more descriptive this could for example be 'for name, age' when combining lists of names and respective ages.

Looping Through a Dictionary

You can loop through a dictionary using the syntax of for key, value in dictionary.items(): loop through key:value tuples as the for x in dictionary goes through each key.

for x in dict:
   print(x) # prints keys
   print(dict[x])   #prints values

Dictionary Comprehension

Like with functions, there is shorthand for creating Python dictionaries as a result of a function. The general syntax for this is

var = { tempvar_key : tempvar_value for tempvar in (list, dict,ect)}

# An example for making a dictionary of cubed numbers:
# Non-comprehension
cubes = {}
for n in (2, 4, 6):
    cubes[n] = n**3

# Dictionary comprehension
cubes = {n: n**3 for n in (2, 4, 6)}

Dictionary Methods

  • clear(): Removes all elements from a dictionary.
  • copy(): Returns a copy of a dictionary.
  • fromkeys(): Returns a new dictionary with the specified keys and values.
  • get(keyname, value): Returns the value of a specified keyname. Returns none if not found or value if put in an optional value.
  • items(): List containing tuples for each key:value pair.
  • keys(): List of keys.
  • pop(): Remove the specified key:value pair.
  • popitem(): Removes last inserted key:value pair.
  • setdefault(): Returns value of specified key. If it does not exist, insert the key with the specified value.
  • update(): Update the dictionary with the specified key:value pairs.
  • values(): Return a list of values in the dictionary.