Skip to content

Instantly share code, notes, and snippets.

@fabsta
Created August 28, 2016 20:25
Show Gist options
  • Save fabsta/83c696009b48389738a8b75f667693ce to your computer and use it in GitHub Desktop.
Save fabsta/83c696009b48389738a8b75f667693ce to your computer and use it in GitHub Desktop.

DICTIONARIES

  • properties: unordered, iterable, mutable, can contain multiple data types
  • made up of key-value pairs
  • keys must be unique, and can be strings, numbers, or tuples
  • values can be any type

create an empty dictionary (two ways)

empty_dict = {}
empty_dict = dict()

create a dictionary (two ways)

family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)

convert a list of tuples into a dictionary

list_of_tuples = [('dad','homer'), ('mom','marge'), ('size', 6)]
family = dict(list_of_tuples)

examine a dictionary

family['dad']       # returns 'homer'
len(family)         # returns 3
family.keys()       # returns list: ['dad', 'mom', 'size']
family.values()     # returns list: ['homer', 'marge', 6]
family.items()      # returns list of tuples:
                    #   [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
'mom' in family     # returns True
'marge' in family   # returns False (only checks keys)

modify a dictionary (does not return the dictionary)

family['cat'] = 'snowball'              # add a new entry
family['cat'] = 'snowball ii'           # edit an existing entry
del family['cat']                       # delete an entry
family['kids'] = ['bart', 'lisa']       # value can be a list
family.pop('dad')                       # removes an entry and returns the value ('homer')
family.update({'baby':'maggie', 'grandpa':'abe'})   # add multiple entries

accessing values more safely with 'get'

family['mom']                       # returns 'marge'
family.get('mom')                   # same thing
family['grandma']                   # throws an error
family.get('grandma')               # returns None
family.get('grandma', 'not found')  # returns 'not found' (the default)

accessing a list element within a dictionary

family['kids'][0]                   # returns 'bart'
family['kids'].remove('lisa')       # removes 'lisa'

string substitution using a dictionary

'youngest child is %(baby)s' % family   # returns 'youngest child is maggie'

Create a dictionary

dict = {'county': ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'], 
        'year': [2012, 2012, 2013, 2014, 2014], 
        'fireReports': [4, 24, 31, 2, 3]}

Create a list from the dictionary keys

Create a list to place the dictionary keys in

dictionaryKeys = []

For each key in the dictionary's keys,

for key in dict.keys():
    # add the key to dictionaryKeys
    dictionaryKeys.append(key)

View the dictionaryKeys list

dictionaryKeys

equivalent list comprehension

items = [item for row in matrix
              for item in row]      # [1, 2, 3, 4]

set comprehension

fruits = ['apple', 'banana', 'cherry']
unique_lengths = {len(fruit) for fruit in fruits}   # {5, 6}

dictionary comprehension

fruit_lengths = {fruit:len(fruit) for fruit in fruits}              # {'apple': 5, 'banana': 6, 'cherry': 6}
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} # {'apple': 0, 'banana': 1, 'cherry': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment