Skip to content

Dictionaries

natalie363 edited this page Nov 3, 2022 · 2 revisions

Dictionary Basics

  • Dictionaries collect data values, but assign them to another piece of data, instead of to an index
  • 'Indexes' for dictionaries are called keys
  • Both pieces of data together are a 'key-value pair'
  • Dictionaries are contained within braces
  • Keys and values are separated by colons
  • Key-value pairs are separated by commas
  • Order does not matter in dictionaries, therefore they cannot be sliced or manipulated by index position
  • Dictionaries are a mutable data type
  • Example: PID = {'hair':'brown', 'height':'5"8'', 'name':'John Doe'}

Functions to use with Dictionaries

  • Use loops along with keys(), values(), and items() to return list-like values
  • dictionaryname.keys() returns all key values when looped
  • dictionaryname.values() returns only the values when looped
  • dictionaryname.items() returns the key-value pairs when looped
  • Use get() to find an item or return a fallback if the value does not exist
  • Get() takes two arguments - key value and a fallback if the key doesn't exist
  • dictionaryname.get('key-value', 'fallback-value')
  • Use setdefault() to set a value for a key if it doesn't currently have a value
  • This takes two arguments - the key to check for and the value to set if the key doesn't exist
  • It is useful to ensure that a key exists and avoid errors
  • dictionaryname.setdefault('key-value', 'value-to-set')
  • The Pretty Printing module provides a cleaner display of values
  • Import the module with import pprint
  • pprint.pprint(dictionaryname) is useful for nested dictionaries and when printing to the string
  • It displays key-value pairs, one per line
  • pprint.pformat(dictionaryname) directs the values to a string instead of printing it to the screen
Clone this wiki locally