Python dictionaries - cheatsheet

Definition

  • Define dictionary (pairs key-value)

    1
    2
    3
    4
    alien_0 = {
    'color': 'green',
    'points': 2
    }
  • Define empty dictionary

    1
    alien_0 = {}
  • Define ordered dictionary (keep order in which the data was entered)

    1
    2
    3
    4
    5
    from collections import OrderedDict 

    fav_languages = OrderedDict()
    fav_languages['angeles'] = ['java', 'python']
    fav_languages['juan'] = ['php', 'java']
  • Get item

    1
    2
    alien_color = alien_0.get('color')
    alien_points = alien_0.get('points', 0)
  • Get lenth

    1
    num_alien_traits = len(alien0)

Basic modifications

  • Add

    1
    alien_0['speed'] = 1.5 
  • Modify

    1
    2
    3
    4
    5
    alien_0 = {
    'color': 'green',
    'points': 2
    }
    alien_0['color'] = 'purple'
  • Remove

    1
    del alien_0['points']

Iteration

  • Loop through items

    1
    2
    for key, value in alien0.items():
    print(key + ": " + value)
  • Loop through keys

    1
    2
    3
    4
    5
    for key in alien0.keys():
    print("key: " + key)

    for key in sorted(alien0.keys()):
    print("key: " + key)
  • Loop through values

    1
    2
    for value in alien0.values():
    print("value: " + value)