• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/10

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

10 Cards in this Set

  • Front
  • Back

dictionary syntax

{ key: value }

What can you place in a dictionary?

the order of the key-value pairs is irrelevant, and the keys must be immutable (no sets or lists or
dictionaries)



+ tuples

Indexing dictionary

Just keys!



right
after the dictionary expression, use square brackets around the key:



{4:"four", 3:'three'}[4]
'four'

Testing membership

'Oracle' in mydict
False

.get()

.get(key, default)



Testing membership and setting up a default error if its not found.

Mutating dictionaries

With the key



>>> mydict['Agent Smith'] = 'Hugo'
>>> mydict['Neo'] = 'Philip'
>>> mydict
{'Neo': 'Philip', 'Agent Smith': 'Hugo', 'Trinity': 'Carrie-Anne',
'Morpheus': 'Laurence'}

dictionary ycomprehensions

>>> { k:v for (k,v) in [(3,2),(4,0),(100,1)] }
{3: 2, 4: 0, 100: 1}
>>> { (x,y):x*y for x in [1,2,3] for y in [1,2,3] }
{(1, 2): 2, (3, 2): 6, (1, 3): 3, (3, 3): 9, (3, 1): 3,
(2, 1): 2, (2, 3): 6, (2, 2): 4, (1, 1): 1}

dictionary functions

.keys() - gets the keys


.values() - gets the values



| and &



| and &

>>> [k for k in {'a':1, 'b':2}.keys() | {'b':3, 'c':4}.keys()]
['a', 'c', 'b']
>>> [k for k in {'a':1, 'b':2}.keys() & {'b':3, 'c':4}.keys()]
['b']

.items()

Turns the dictionary key values into tuples



>>> [myitem for myitem in mydict.items()]
[('Neo', 'Philip'), ('Morpheus', 'Laurence'),
('Trinity', 'Carrie-Anne'), ('Agent Smith', 'Hugo')]
Since the items are tuples, you can access the key and value separately using unpacking:
>>> [k + " is played by " + v for (k,v) in mydict.items()]
['Neo is played by Philip, 'Agent Smith is played by Hugo',
'Trinity is played by Carrie-Anne', 'Morpheus is played by Laurence']
>>> [2*k+v for (k,v) in {4:0,3:2, 100:1}.items() ]
[8, 8, 201]