Appendix D: Working With Dictionaries

 

=> marks the start of the output

 

clear( )

 

Removes all elements of the dictionary, returning an empty dictionary

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

print (dic1)

=> {1: 'one', 2: 'two'}

 

dic1.clear()

print (dic1)

=> { }

 

del

 

Delete the entire dictionary

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

del dic1

print (dic1)

=> NameError: name 'dic1' is not defined

 

get( )

 

Returns a value for the given key.

If the key is not found, it’ll return the keyword None.

Alternatively, you can state the value to return if the key is not found.

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

dic1.get(1)

=> ‘one’

 

dic1.get(5)

=> None

 

dic1.get(5, “Not Found”)

=> ‘Not Found’

 

In

 

Check if an item is in a dictionary

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

 

# based on the key

1 in dic1

=> True

 

3 in dic1

=> False

 

# based on the value

‘one’ in dic1.values()

=> True

 

‘three’ in dic1.values()

=> False

 

items( )

 

Returns a list of dictionary’s pairs as tuples

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

dic1.items()

=> dict_items([(1, 'one'), (2, 'two')])

 

keys( )

 

Returns list of the dictionary's keys

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

dic1.keys()

=> dict_keys([1, 2])

 

len( )

 

Find the number of items in a dictionary

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

print (len(dic1))

=> 2

 

update( )

 

Adds one dictionary’s key-values pairs to another. Duplicates are removed.

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

dic2 = {1: ‘one’, 3: ‘three’}

 

dic1.update(dic2)

print (dic1)

=> {1: 'one', 2: 'two', 3: 'three'}

 

print (dic2) #no change

=> {1: ‘one’, 3: ‘three’}

 

values( )

 

Returns list of the dictionary's values

 

[Example]

 

dic1 = {1: ‘one’, 2: ‘two’}

dic1.values()

=> dict_values(['one', 'two'])