 Prev: Dictionary vs. List       |       Next: The 'tuple' object

# Dictionary functions and methods¶

### Functions¶

#### len(dict)¶

Returns the 'length' of the dict: the number of key:value items

In :
di = {x:chr(x) for x in range(65,75)}
print(di)
len(di)

{65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E', 70: 'F', 71: 'G', 72: 'H', 73: 'I', 74: 'J'}

Out:
10

#### max(dict), min(dict)¶

Returns the largest and smallest key values in the dict

In :
di = {x:chr(x) for x in range(65,75)}
print(max(di), min(di))

74 65


#### sorted(dict)¶

Returns a new list including the sorted key values (numerics or strings) of the dict

In :
import random
di = {random.randint(1,100):chr(x) for x in range(65,70)}
print(di,'\n')
print(sorted(di))

{16: 'E', 49: 'A', 3: 'C', 52: 'D', 93: 'B'}

[3, 16, 49, 52, 93]


#### sum(dict)¶

Returns the sum of numeric keys in a dict. Raises a TypeError exception if keys are not numerics

In :
import random
di = {random.randint(1,100):chr(x) for x in range(65,67)}
print(di,'\n')
print(sum(di))

{1: 'A', 43: 'B'}

44

• See all Python built-in functions here ### Methods¶

#### dict.keys(), dict.values()¶

Return a dict_keys and dict_values objects respectively. These are sequences including the keys and values of a dict. By passing them to a list() constructor you get the key and value lists of the dict (unsorted!)

In :
import random
di = {random.randint(1,100):chr(x) for x in range(65,70)}
print(di,'\n')
list(di.keys()), list(di.values())

{16: 'C', 70: 'D', 45: 'A', 94: 'B', 71: 'E'}


Out:
([16, 70, 45, 94, 71], ['C', 'D', 'A', 'B', 'E'])

#### dict.get(key)¶

Returns the value of the key. If no such key exists then a predefined default message appears.

In :
di = {x:chr(x) for x in range(65,70)}
di.get(65, 'No such key'), di.get(10, 'No such key')

Out:
('A', 'No such key')

#### dict.items()¶

Returns an iterable object having as items the 'key:value' tuples of the dict. Commonly used in 'for' loops.

In :
di = {x:chr(x) for x in range(65,70)}
for it in di.items():
print('Key: {:3}, Value: {:3}'.format(it,it))

Key:  65, Value: A
Key:  66, Value: B
Key:  67, Value: C
Key:  68, Value: D
Key:  69, Value: E


#### dict1.update(dict2)¶

Updates the items in dict1 with the items of dict2

• If a key in dict2 already exists in dict1 then the value in dict1 is updated
• If a key in dict2 is not included in dict1 then the key:value item of dict2 is added in dict1
In :
di1 = {x:chr(x) for x in range(65,70)}
di2 = {x:chr(x+1) for x in range(67,72)}
print('di1 = ',di1)
print('di2 = ',di2)
di1.update(di2)
print('Updated di1 = ',di1)

di1 =  {65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E'}
di2 =  {67: 'D', 68: 'E', 69: 'F', 70: 'G', 71: 'H'}
Updated di1 =  {65: 'A', 66: 'B', 67: 'D', 68: 'E', 69: 'F', 70: 'G', 71: 'H'}


#### dict.copy()¶

Creates a shallow copy of the dict. Recall: 'shallow' means that the nested mutable items (for example, lists and other dicts) are NOT copied. So, any change in their values referencing the copied dict will also affect the original.

• For a deep copy you need to import the copy module and use the deepcopy() method instead.
In :
import copy
diorig = {1:'A', 2:[10,20,30]}
print('diorig = ',diorig)
dicopy = diorig.copy()
print('dicopy = ',dicopy,'\n')

dicopy='X'
print('dicopy = ',dicopy)
print('diorig = ',diorig)   # With shallow copy() the original dict appears also changed

diorig =  {1: 'A', 2: [10, 20, 30]}
dicopy =  {1: 'A', 2: [10, 20, 30]}

dicopy =  {1: 'A', 2: ['X', 20, 30]}
diorig =  {1: 'A', 2: ['X', 20, 30]}


#### dict.fromkeys(keys [, value])¶

Constructs a new dictionary from a list of keys.

• If 'value' is omitted then the values in the new dict are all set to 'None'.
• If 'value' is defined then all pairs will have the same value. Keep in mind that later changes on the 'value' object will reflect on all pairs, since all dict keys point to the same 'value' obect.
In :
keys = 'sequence'
value = []
di = dict.fromkeys(keys, value)
print(di)
di['e'].append(1)
print(di)

{'e': [], 's': [], 'u': [], 'c': [], 'q': [], 'n': []}
{'e': , 's': , 'u': , 'c': , 'q': , 'n': }  . Free learning material
. See full copyright and disclaimer notice