Functions & methods to manipulate Dictionaries

Some dictionary functions

len(dict) reports the number of key:value pairs in a dictionary

in and not in keywords check if a specific key exists in a dictionary.

Examples:

fruits = {'apple' : 2, 'banana' : 1, 'pear' : 6}

print('pear' in fruits)      # True
print('kiwi' in fruits)      # False    

fruits['kiwi'] = 0
print(fruits)                # {'banaba':1, 'apple':2, 'pear': 6, 'kiwi':0}

fruits['kiwi'] += 10 

print(fruits)                # {'banaba':1, 'apple':2, 'pear': 6, 'kiwi':10}

print(len(fruits))           # 4

More useful functions:

list(d.keys()) returns a list of all the keys used in the dictionary, in arbitrary order.
list(d.values()) returns a list of all the values in the dictionary.
sorted(d.keys()) returns a sorted list of all keys.

Some dictionary methods

d.keys() returns all keys in d.
d.values() returns all values in d.
d.pop(key) removes a key and returns its corresponding value.
d.clear() removes all items from d.

fruits.pop('apple')
print(fruits)        # {'banaba':8, 'kiwi':10}

fruits.clear()  
print(fruits)        # { }  (empty dictionary)
print(len(fruits))   # 0  (no elements)

results matching ""

    No results matching ""